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

// 고객사별 수주 건수 (파이차트용)
// 원본: contractMgmt.xml getContractCNTBySupply
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 year = String(body.Year || body.year || new Date().getFullYear());

  const rows = await queryRows(
    `SELECT
      ASM.objid::text AS "OBJID",
      ASM.supply_name AS "SUPPLY_NAME",
      S1.total_cnt AS "TOTAL_SUPPLY_UNIT_CNT"
    FROM supply_mng ASM
    JOIN (
      SELECT CM.customer_objid, COUNT(1) AS total_cnt
      FROM contract_mgmt CM
      WHERE CM.contract_result = '0000964'
        AND TO_CHAR(TO_DATE(CM.contract_date,'YYYY-MM-DD'),'YYYY') = $1
      GROUP BY CM.customer_objid
    ) S1 ON ASM.objid::varchar = S1.customer_objid
    ORDER BY S1.total_cnt DESC, ASM.supply_name`,
    [year]
  );

  return NextResponse.json({ success: true, rows });
}
