/**
 * KPI 컨트롤러 — TASK:ERP-022
 * 일별 생산량 등 KPI 지표 조회 전담
 */
import { Response } from "express";
import { AuthenticatedRequest } from "../types/auth";
import { getPool } from "../database/db";
import { logger } from "../utils/logger";

/**
 * GET /api/kpi/daily-production?from=YYYY-MM-DD&to=YYYY-MM-DD
 * 회사별 일별 생산량 조회
 */
export async function getDailyProduction(req: AuthenticatedRequest, res: Response) {
  try {
    const companyCode = req.user?.companyCode;
    if (!companyCode) {
      return res.status(401).json({ success: false, message: "인증 필요" });
    }

    const from = (req.query.from as string) || "";
    const to = (req.query.to as string) || "";

    const params: any[] = [companyCode];
    let where = "company_code = $1";
    if (from) {
      params.push(from);
      where += ` AND prod_date >= $${params.length}`;
    }
    if (to) {
      params.push(to);
      where += ` AND prod_date <= $${params.length}`;
    }

    const result = await getPool().query(
      `SELECT prod_date, production_qty, defect_qty, work_hours, remark
       FROM kpi_daily_production
       WHERE ${where}
       ORDER BY prod_date`,
      params
    );

    return res.json({ success: true, data: result.rows });
  } catch (error: any) {
    logger.error("KPI 일별 생산량 조회 실패", { error: error.message });
    return res.status(500).json({ success: false, message: error.message });
  }
}
