/**
 * 차량 운행 리포트 컨트롤러
 */
import { Response } from "express";
import { AuthenticatedRequest } from "../middleware/authMiddleware";
import { vehicleReportService } from "../services/vehicleReportService";

/**
 * 일별 통계 조회
 * GET /api/vehicle/reports/daily
 */
export const getDailyReport = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<Response | void> => {
  try {
    const { companyCode } = req.user as any;
    const { startDate, endDate, userId, vehicleId } = req.query;

    console.log("📊 [getDailyReport] 요청:", { companyCode, startDate, endDate });

    const result = await vehicleReportService.getDailyReport(companyCode, {
      startDate: startDate as string,
      endDate: endDate as string,
      userId: userId as string,
      vehicleId: vehicleId ? parseInt(vehicleId as string) : undefined,
    });

    res.json({
      success: true,
      data: result,
    });
  } catch (error: any) {
    console.error("❌ [getDailyReport] 실패:", error);
    res.status(500).json({
      success: false,
      message: error.message || "일별 통계 조회에 실패했습니다.",
    });
  }
};

/**
 * 주별 통계 조회
 * GET /api/vehicle/reports/weekly
 */
export const getWeeklyReport = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<Response | void> => {
  try {
    const { companyCode } = req.user as any;
    const { year, month, userId, vehicleId } = req.query;

    console.log("📊 [getWeeklyReport] 요청:", { companyCode, year, month });

    const result = await vehicleReportService.getWeeklyReport(companyCode, {
      year: year ? parseInt(year as string) : new Date().getFullYear(),
      month: month ? parseInt(month as string) : new Date().getMonth() + 1,
      userId: userId as string,
      vehicleId: vehicleId ? parseInt(vehicleId as string) : undefined,
    });

    res.json({
      success: true,
      data: result,
    });
  } catch (error: any) {
    console.error("❌ [getWeeklyReport] 실패:", error);
    res.status(500).json({
      success: false,
      message: error.message || "주별 통계 조회에 실패했습니다.",
    });
  }
};

/**
 * 월별 통계 조회
 * GET /api/vehicle/reports/monthly
 */
export const getMonthlyReport = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<Response | void> => {
  try {
    const { companyCode } = req.user as any;
    const { year, userId, vehicleId } = req.query;

    console.log("📊 [getMonthlyReport] 요청:", { companyCode, year });

    const result = await vehicleReportService.getMonthlyReport(companyCode, {
      year: year ? parseInt(year as string) : new Date().getFullYear(),
      userId: userId as string,
      vehicleId: vehicleId ? parseInt(vehicleId as string) : undefined,
    });

    res.json({
      success: true,
      data: result,
    });
  } catch (error: any) {
    console.error("❌ [getMonthlyReport] 실패:", error);
    res.status(500).json({
      success: false,
      message: error.message || "월별 통계 조회에 실패했습니다.",
    });
  }
};

/**
 * 요약 통계 조회 (대시보드용)
 * GET /api/vehicle/reports/summary
 */
export const getSummaryReport = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<Response | void> => {
  try {
    const { companyCode } = req.user as any;
    const { period } = req.query; // today, week, month, year

    console.log("📊 [getSummaryReport] 요청:", { companyCode, period });

    const result = await vehicleReportService.getSummaryReport(
      companyCode,
      (period as string) || "today"
    );

    res.json({
      success: true,
      data: result,
    });
  } catch (error: any) {
    console.error("❌ [getSummaryReport] 실패:", error);
    res.status(500).json({
      success: false,
      message: error.message || "요약 통계 조회에 실패했습니다.",
    });
  }
};

/**
 * 운전자별 통계 조회
 * GET /api/vehicle/reports/by-driver
 */
export const getDriverReport = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<Response | void> => {
  try {
    const { companyCode } = req.user as any;
    const { startDate, endDate, limit } = req.query;

    console.log("📊 [getDriverReport] 요청:", { companyCode, startDate, endDate });

    const result = await vehicleReportService.getDriverReport(companyCode, {
      startDate: startDate as string,
      endDate: endDate as string,
      limit: limit ? parseInt(limit as string) : 10,
    });

    res.json({
      success: true,
      data: result,
    });
  } catch (error: any) {
    console.error("❌ [getDriverReport] 실패:", error);
    res.status(500).json({
      success: false,
      message: error.message || "운전자별 통계 조회에 실패했습니다.",
    });
  }
};

/**
 * 구간별 통계 조회
 * GET /api/vehicle/reports/by-route
 */
export const getRouteReport = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<Response | void> => {
  try {
    const { companyCode } = req.user as any;
    const { startDate, endDate, limit } = req.query;

    console.log("📊 [getRouteReport] 요청:", { companyCode, startDate, endDate });

    const result = await vehicleReportService.getRouteReport(companyCode, {
      startDate: startDate as string,
      endDate: endDate as string,
      limit: limit ? parseInt(limit as string) : 10,
    });

    res.json({
      success: true,
      data: result,
    });
  } catch (error: any) {
    console.error("❌ [getRouteReport] 실패:", error);
    res.status(500).json({
      success: false,
      message: error.message || "구간별 통계 조회에 실패했습니다.",
    });
  }
};

