package com.datacenter.controller;

import com.datacenter.entity.resp.MessageResult;
import com.datacenter.entity.stat.StatContractPnl;
import com.datacenter.entity.stat.StatPlatformDailyPnl;
import com.datacenter.entity.stat.StatTodayOverview;
import com.datacenter.service.StatContractPnlService;
import com.datacenter.service.StatCopyTradePositionService;
import com.datacenter.service.StatPlatformDailyPnlService;
import com.datacenter.service.StatTodayOverviewService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * 手动触发定时任务的内部接口，供 admin 管理后台"刷新"按钮调用。
 * 路径已在 WebMvcConfig 中排除鉴权。
 */
@Slf4j
@RestController
@RequestMapping("/job/run")
@RequiredArgsConstructor
public class JobController {

    private final StatTodayOverviewService       statTodayOverviewService;
    private final StatContractPnlService         statContractPnlService;
    private final StatPlatformDailyPnlService    statPlatformDailyPnlService;
    private final StatCopyTradePositionService   statCopyTradePositionService;

    /**
     * 立即执行今日概览统计任务（同时计算两个变体），返回指定模式的最新结果。
     * POST /job/run/today-overview?includeInternal=0
     */
    @PostMapping("/today-overview")
    public MessageResult runTodayOverview(
            @RequestParam(value = "includeInternal", defaultValue = "0") int includeInternal) {
        log.info("[JobController] 手动触发今日概览统计 includeInternal={}", includeInternal);
        statTodayOverviewService.computeAndSaveBoth(LocalDate.now());
        StatTodayOverview result = statTodayOverviewService.getByDate(LocalDate.now(), includeInternal == 1);
        return MessageResult.success("SUCCESS", result);
    }

    /**
     * 立即执行合约盈亏统计任务，返回指定模式的最新结果。
     * POST /job/run/contract-pnl?includeInternal=0
     */
    @PostMapping("/contract-pnl")
    public MessageResult runContractPnl(
            @RequestParam(value = "includeInternal", defaultValue = "0") int includeInternal) {
        log.info("[JobController] 手动触发合约盈亏统计 includeInternal={}", includeInternal);
        statContractPnlService.computeAndSaveBoth(LocalDate.now());
        StatContractPnl result = statContractPnlService.getByDate(LocalDate.now(), includeInternal == 1);
        return MessageResult.success("SUCCESS", result);
    }

    /**
     * 补算过去 N 天的历史概览数据（含充值提现），供 daily-recharge 图表使用。
     * POST /job/run/today-overview/backfill?days=30
     */
    @PostMapping("/today-overview/backfill")
    public MessageResult backfillTodayOverview(
            @RequestParam(value = "days", defaultValue = "30") int days) {
        log.info("[JobController] 回填历史概览统计 days={}", days);
        statTodayOverviewService.backfill(days);
        return MessageResult.success("SUCCESS", "已回填 " + days + " 天历史数据");
    }

    /**
     * 补算过去 N 天的历史每日盈亏数据。
     * POST /job/run/contract-pnl/backfill?days=30
     */
    @PostMapping("/contract-pnl/backfill")
    public MessageResult backfillContractPnl(
            @RequestParam(value = "days", defaultValue = "30") int days) {
        log.info("[JobController] 回填历史合约盈亏统计 days={}", days);
        statContractPnlService.backfill(days);
        return MessageResult.success("SUCCESS", "已回填 " + days + " 天历史数据");
    }

    /**
     * 立即执行平台每日盈亏统计（统计今日数据）。
     * POST /job/run/platform-daily-pnl?includeInternal=0
     */
    @PostMapping("/platform-daily-pnl")
    public MessageResult runPlatformDailyPnl(
            @RequestParam(value = "includeInternal", defaultValue = "0") int includeInternal) {
        log.info("[JobController] 手动触发平台每日盈亏统计 includeInternal={}", includeInternal);
        statPlatformDailyPnlService.computeAndSaveBoth(LocalDate.now());
        StatPlatformDailyPnl result = statPlatformDailyPnlService.getByDate(LocalDate.now(), includeInternal == 1);
        return MessageResult.success("SUCCESS", result);
    }

    /**
     * 补算过去 N 天的平台每日盈亏历史数据。
     * POST /job/run/platform-daily-pnl/backfill?days=30
     */
    @PostMapping("/platform-daily-pnl/backfill")
    public MessageResult backfillPlatformDailyPnl(
            @RequestParam(value = "days", defaultValue = "30") int days) {
        log.info("[JobController] 回填平台每日盈亏统计 days={}", days);
        statPlatformDailyPnlService.backfill(days);
        return MessageResult.success("SUCCESS", "已回填 " + days + " 天历史数据");
    }

    /**
     * 立即执行跟单持仓快照统计。
     * POST /job/run/copy-trade-position
     * Body（可选）: {"BTC/USDT": 95000.0, "ETH/USDT": 2316.97, ...}
     */
    @PostMapping("/copy-trade-position")
    public MessageResult runCopyTradePosition(
            @RequestBody(required = false) Map<String, BigDecimal> prices) {
        log.info("[JobController] 手动触发跟单持仓快照统计 externalPrices={}",
                prices != null ? prices.size() : 0);
        if (prices != null && !prices.isEmpty()) {
            statCopyTradePositionService.computeAndSave(prices);
        } else {
            statCopyTradePositionService.computeAndSave();
        }
        return MessageResult.success("SUCCESS", "跟单持仓快照已更新");
    }
}
