package com.market.controller;

import com.market.entity.ContractCoin;
import com.market.model.request.KlineSyncRequest;
import com.market.service.ContractCoinService;
import com.market.service.KlineSyncService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * K 线历史数据同步接口
 */
@Slf4j
@RestController
@RequestMapping("/api/kline")
public class KlineSyncController {

    private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");

    @Autowired
    private KlineSyncService klineSyncService;
    @Autowired
    private ContractCoinService contractCoinService;

    /**
     * 同步 K 线数据到数据库
     *
     * <pre>
     * POST /api/kline/sync
     * {
     *   "from":     "2024-03-01",   // 开始日期（必填）
     *   "to":       "2024-03-08",   // 结束日期（必填）
     *   "symbol":   "btcusdt",      // 可选，不传则同步所有启用交易对
     *   "interval": "1m"            // 可选，不传则同步所有支持周期
     * }
     * </pre>
     */
    @PostMapping("/sync")
    public ResponseEntity<?> sync(@RequestBody KlineSyncRequest request) {
        if (request.getFrom() == null || request.getTo() == null) {
            return ResponseEntity.badRequest().body(Map.of("error", "from 和 to 不能为空"));
        }
        long fromMs, toMs;
        try {
            LocalDate fromDate = LocalDate.parse(request.getFrom(), DATE_FMT);
            LocalDate toDate   = LocalDate.parse(request.getTo(),   DATE_FMT);
            if (fromDate.isAfter(toDate)) {
                return ResponseEntity.badRequest().body(Map.of("error", "from 不能晚于 to"));
            }
            // from 取当天 00:00:00，to 取当天 23:59:59.999
            fromMs = fromDate.atStartOfDay(ZONE).toInstant().toEpochMilli();
            toMs   = toDate.atTime(23, 59, 59, 999_000_000).atZone(ZONE).toInstant().toEpochMilli();
        } catch (DateTimeParseException e) {
            return ResponseEntity.badRequest().body(Map.of("error", "日期格式错误，请使用 yyyy-MM-dd"));
        }

        log.info("K 线同步开始: from={} to={} symbol={} interval={}",
                request.getFrom(), request.getTo(), request.getSymbol(), request.getInterval());

        List<String> symbols;
        if (StringUtils.isNotBlank(request.getSymbol())) {
            symbols = Collections.singletonList(request.getSymbol().replace("/", "").toLowerCase());
        } else {
            symbols = contractCoinService.listEnabled().stream()
                    .map(ContractCoin::getSymbol)
                    .filter(StringUtils::isNotBlank)
                    .map(s -> s.replace("/", "").toLowerCase())
                    .distinct()
                    .collect(Collectors.toList());
        }
        Map<String, Object> result = klineSyncService.sync(fromMs, toMs, request.getSymbol(), request.getInterval(), symbols);
        log.info("K 线同步完成: {}", result);
        return ResponseEntity.ok(result);
    }
}
