package com.bizzan.bitrade.controller.authno;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Map;

/**
 * 内部免鉴权接口，供 datacenter 定时任务拉取合约实时价格。
 * 路径 /noauth/** 已在 ShiroConfig 中排除鉴权。
 */
@Slf4j
@RestController
@RequestMapping("/noauth")
public class InternalPriceController {

    /** Eureka/Ribbon 负载均衡 RestTemplate，可解析 contract-swap-api 等服务名 */
    @Autowired
    private RestTemplate restTemplate;

    /**
     * POST /noauth/swap-prices
     * 透传 contract-swap-api 的实时价格 Map，给 datacenter 定时任务使用。
     */
    @PostMapping("/swap-prices")
    public Map<String, BigDecimal> swapPrices() {
        try {
            String url = "http://contract-swap-api/swap/symbol-price";
            ParameterizedTypeReference<Map<String, BigDecimal>> typeRef =
                    new ParameterizedTypeReference<Map<String, BigDecimal>>() {};
            ResponseEntity<Map<String, BigDecimal>> resp =
                    restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(null), typeRef);
            if (resp.getBody() != null) {
                log.debug("[InternalPrice] 返回 {} 个交易对价格", resp.getBody().size());
                return resp.getBody();
            }
        } catch (Exception e) {
            log.warn("[InternalPrice] 获取合约价格失败: {}", e.getMessage());
        }
        return Collections.emptyMap();
    }
}
