import { Request, Response } from "express";
import dashboardService from "../services/dashboardService";

class DashboardController {
  /**
   * 获取 KPI 数据：日活用户数、日活曲线、广告收益、收益曲线
   * GET /api/dashboard/kpi?dateRange=7
   * @param req Express 请求对象
   * @param res Express 响应对象
   */
  public async getKpi(req: Request, res: Response): Promise<void> {
    try {
      const dateRange = Math.min(Math.max(parseInt(req.query.dateRange as string) || 7, 1), 90); // 1-90 天

      console.log(`[DashboardController] getKpi start, dateRange=${dateRange}`);
      const startedAt = Date.now();

      const kpiData = await dashboardService.getKpi(dateRange);

      console.log(`[DashboardController] getKpi end, durationMs=${Date.now() - startedAt}`);

      res.status(200).json({
        success: true,
        data: kpiData,
      });
    } catch (error: any) {
      console.error("[DashboardController] Error in getKpi:", error);
      res.status(500).json({
        success: false,
        message: "Failed to fetch KPI data",
        error: error.message,
      });
    }
  }

  /**
   * 获取作品统计数据：点击率、完成率排行
   * GET /api/dashboard/artwork-stats?top=10&sortBy=clickRate
   * @param req Express 请求对象
   * @param res Express 响应对象
   */
  public async getArtworkStats(req: Request, res: Response): Promise<void> {
    try {
      const top = Math.min(Math.max(parseInt(req.query.top as string) || 10, 1), 100); // 1-100 件
      const sortBy = (req.query.sortBy as string) || "clickCount"; // clickRate | completionRate | clickCount | completionCount

      // 验证 sortBy 值
      const validSortByValues = ["clickRate", "completionRate", "clickCount", "completionCount"];
      if (!validSortByValues.includes(sortBy)) {
        res.status(400).json({
          success: false,
          message: `Invalid sortBy value. Expected one of: ${validSortByValues.join(", ")}`,
        });
        return;
      }

      console.log(`[DashboardController] getArtworkStats start, top=${top}, sortBy=${sortBy}`);
      const startedAt = Date.now();

      const artworkStats = await dashboardService.getArtworkStats(top, sortBy as "clickRate" | "completionRate" | "clickCount" | "completionCount");

      console.log(`[DashboardController] getArtworkStats end, durationMs=${Date.now() - startedAt}`);

      res.status(200).json({
        success: true,
        data: artworkStats,
      });
    } catch (error: any) {
      console.error("[DashboardController] Error in getArtworkStats:", error);
      res.status(500).json({
        success: false,
        message: "Failed to fetch artwork stats",
        error: error.message,
      });
    }
  }

  /**
   * 获取最近 N 天上新作品分日数据（用于 tab 展示）
   * GET /api/dashboard/new-artwork-tabs?days=7&topPerDay=20
   */
  public async getNewArtworkTabs(req: Request, res: Response): Promise<void> {
    try {
      const days = Math.min(Math.max(parseInt(req.query.days as string) || 7, 1), 30);
      const topPerDay = Math.min(Math.max(parseInt(req.query.topPerDay as string) || 20, 1), 100);

      console.log(`[DashboardController] getNewArtworkTabs start, days=${days}, topPerDay=${topPerDay}`);
      const startedAt = Date.now();

      const data = await dashboardService.getNewArtworkTabs(days, topPerDay);

      console.log(`[DashboardController] getNewArtworkTabs end, durationMs=${Date.now() - startedAt}`);

      res.status(200).json({
        success: true,
        data,
      });
    } catch (error: any) {
      console.error("[DashboardController] Error in getNewArtworkTabs:", error);
      res.status(500).json({
        success: false,
        message: "Failed to fetch new artwork tabs",
        error: error.message,
      });
    }
  }
}

const dashboardController = new DashboardController();
export default dashboardController;
