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

// 프로젝트관리 메인 목록 (수주 확정된 계약 기반)
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[] = ["CM.contract_result = '0000964'"];
  const params: unknown[] = [];
  let idx = 1;

  if (body.year) {
    conditions.push(`TO_CHAR(TO_DATE(CM.contract_date, 'YYYY-MM-DD'), 'YYYY') = $${idx++}`);
    params.push(body.year);
  }
  if (body.project_no) {
    conditions.push(`CM.contract_no LIKE '%' || $${idx++} || '%'`);
    params.push(body.project_no);
  }
  if (body.project_name) {
    conditions.push(`CM.project_name LIKE '%' || $${idx++} || '%'`);
    params.push(body.project_name);
  }

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

  const rows = await queryRows(
    `SELECT CM.objid::text AS "OBJID",
       CM.contract_no AS "PROJECT_NO",
       CM.project_name AS "PROJECT_NAME",
       COALESCE((SELECT supply_name FROM supply_mng WHERE objid::text = CM.customer_objid LIMIT 1), '') AS "CUSTOMER_NAME",
       COALESCE((SELECT code_name FROM comm_code WHERE code_id = CM.product LIMIT 1), '') AS "PRODUCT_NAME",
       COALESCE((SELECT code_name FROM comm_code WHERE code_id = CM.manufacture_plant LIMIT 1), '') AS "MANUFACTURE_PLANT_NAME",
       COALESCE((SELECT code_name FROM comm_code WHERE code_id = CM.contract_result LIMIT 1), '') AS "STATUS",
       COALESCE((SELECT user_name FROM user_info WHERE user_id = CM.pm_user_id LIMIT 1), '') AS "PM_NAME",
       CM.contract_del_date AS "START_DATE",
       CM.req_del_date AS "END_DATE",
       0 AS "TOTAL_RATE"
     FROM contract_mgmt CM
     WHERE ${where}
     ORDER BY CM.regdate DESC
`,
    params
  );

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