import { NextRequest, NextResponse } from "next/server";
import { queryRows } from "@/lib/db";
import { getSession } from "@/lib/session";

// CS 차트 데이터 (getAsTotalList_CS / getASDashboardList 대응)
// 년도/제품별 CS 건수 집계 + 유/무상 구분
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json();
  const conditions: string[] = ["1=1"];
  const params: unknown[] = [];
  let idx = 1;

  if (body.year) {
    conditions.push(`A.year = $${idx++}`);
    params.push(body.year);
  }
  if (body.product_code) {
    conditions.push(`A.product_code = $${idx++}`);
    params.push(body.product_code);
  }

  const where = conditions.join(" AND ");

  // 제품별 CS 건수 + 유/무상 구분
  const rows = await queryRows(
    `SELECT
       COALESCE(A.product_name, (SELECT code_name FROM comm_code WHERE code_id = A.product_code LIMIT 1), '미분류') AS "PRODUCT_NAME",
       COUNT(*) AS "TOTAL_CNT",
       COUNT(CASE WHEN A.paid_free = '유상' OR A.warranty_code = '0000157' THEN 1 END) AS "PAID_CNT",
       COUNT(CASE WHEN A.paid_free = '무상' OR A.warranty_code = '0000158' THEN 1 END) AS "FREE_CNT",
       COUNT(CASE WHEN A.status_cd = 'AS_STATUS_03' OR A.status_cd = '0000102' THEN 1 END) AS "COMPLETE_CNT",
       COUNT(CASE WHEN A.status_cd IS NULL OR (A.status_cd != 'AS_STATUS_03' AND A.status_cd != '0000102') THEN 1 END) AS "INCOMPLETE_CNT",
       -- 월별 건수 (차트용)
       COUNT(CASE WHEN EXTRACT(MONTH FROM A.reg_date) = 1 THEN 1 END) AS "M01",
       COUNT(CASE WHEN EXTRACT(MONTH FROM A.reg_date) = 2 THEN 1 END) AS "M02",
       COUNT(CASE WHEN EXTRACT(MONTH FROM A.reg_date) = 3 THEN 1 END) AS "M03",
       COUNT(CASE WHEN EXTRACT(MONTH FROM A.reg_date) = 4 THEN 1 END) AS "M04",
       COUNT(CASE WHEN EXTRACT(MONTH FROM A.reg_date) = 5 THEN 1 END) AS "M05",
       COUNT(CASE WHEN EXTRACT(MONTH FROM A.reg_date) = 6 THEN 1 END) AS "M06",
       COUNT(CASE WHEN EXTRACT(MONTH FROM A.reg_date) = 7 THEN 1 END) AS "M07",
       COUNT(CASE WHEN EXTRACT(MONTH FROM A.reg_date) = 8 THEN 1 END) AS "M08",
       COUNT(CASE WHEN EXTRACT(MONTH FROM A.reg_date) = 9 THEN 1 END) AS "M09",
       COUNT(CASE WHEN EXTRACT(MONTH FROM A.reg_date) = 10 THEN 1 END) AS "M10",
       COUNT(CASE WHEN EXTRACT(MONTH FROM A.reg_date) = 11 THEN 1 END) AS "M11",
       COUNT(CASE WHEN EXTRACT(MONTH FROM A.reg_date) = 12 THEN 1 END) AS "M12"
     FROM as_mng A
     WHERE ${where}
     GROUP BY A.product_code, A.product_name
     ORDER BY "TOTAL_CNT" DESC`,
    params
  );

  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
