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

// 영업관리 > 계약관리 목록 (원본: contractMgmt.xml contractGridList + contractBase)
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 || body.year) {
    conditions.push(`SUBSTR(CM.contract_date, 1, 4) = $${idx++}`);
    params.push(String(body.Year || body.year));
  }
  if (body.category_cd) {
    conditions.push(`CM.category_cd = $${idx++}`);
    params.push(body.category_cd);
  }
  if (body.customer_objid) {
    conditions.push(`CM.customer_objid = $${idx++}`);
    params.push(body.customer_objid);
  }
  if (body.product) {
    conditions.push(`CM.product = $${idx++}`);
    params.push(body.product);
  }
  if (body.contract_result) {
    conditions.push(`CM.contract_result = $${idx++}`);
    params.push(body.contract_result);
  }
  if (body.pm_user_id) {
    conditions.push(`CM.pm_user_id = $${idx++}`);
    params.push(body.pm_user_id);
  }
  if (body.contract_start_date) {
    conditions.push(`TO_DATE(CM.contract_date,'YYYY-MM-DD') >= TO_DATE($${idx++},'YYYY-MM-DD')`);
    params.push(body.contract_start_date);
  }
  if (body.contract_end_date) {
    conditions.push(`TO_DATE(CM.contract_date,'YYYY-MM-DD') <= TO_DATE($${idx++},'YYYY-MM-DD')`);
    params.push(body.contract_end_date);
  }

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

  const sql = `
    SELECT CM.objid::text AS "OBJID",
      CM.contract_no AS "CONTRACT_NO",
      CM.category_cd AS "CATEGORY_CD",
      (SELECT code_name FROM comm_code WHERE code_id = CM.category_cd LIMIT 1) AS "CATEGORY_NAME",
      CM.overhaul_order AS "OVERHAUL_ORDER",
      CM.area_cd AS "AREA_CD",
      (SELECT code_name FROM comm_code WHERE code_id = CM.area_cd LIMIT 1) AS "AREA_NAME",
      CM.customer_objid AS "CUSTOMER_OBJID",
      (SELECT supply_name FROM supply_mng WHERE objid::text = CM.customer_objid LIMIT 1) AS "CUSTOMER_NAME",
      CM.product AS "PRODUCT",
      (SELECT code_name FROM comm_code WHERE code_id = CM.product LIMIT 1) AS "PRODUCT_NAME",
      CM.mechanical_type AS "MECHANICAL_TYPE",
      CM.customer_project_name AS "CUSTOMER_PROJECT_NAME",
      CM.due_date AS "DUE_DATE",
      CM.location AS "LOCATION",
      CM.setup AS "SETUP",
      CM.facility AS "FACILITY",
      (SELECT code_name FROM comm_code WHERE code_id = CM.facility LIMIT 1) AS "FACILITY_NAME",
      CM.facility_qty AS "FACILITY_QTY",
      CM.facility_type AS "FACILITY_TYPE",
      CM.facility_depth AS "FACILITY_DEPTH",
      CM.writer AS "WRITER",
      (SELECT user_name FROM user_info WHERE user_id = CM.writer LIMIT 1) AS "WRITER_NAME",
      TO_CHAR(CM.regdate,'YYYY-MM-DD') AS "REG_DATE",
      (SELECT COUNT(*) FROM attach_file_info WHERE target_objid = CM.objid::text AND doc_type='contractMgmt01' AND UPPER(COALESCE(status,'active'))='ACTIVE')::text AS "CU01_CNT",
      (CASE WHEN (CM.result_cd IS NULL OR CM.result_cd='') AND (CM.spec_result_cd IS NULL OR CM.spec_result_cd='') AND (CM.est_result_cd IS NULL OR CM.est_result_cd='') THEN '0' ELSE '1' END) AS "CU03_CNT",
      CM.contract_result AS "CONTRACT_RESULT",
      (SELECT code_name FROM comm_code WHERE code_id = CM.contract_result LIMIT 1) AS "CONTRACT_RESULT_NAME",
      CM.contract_date AS "CONTRACT_DATE",
      CM.po_no AS "PO_NO",
      CM.pm_user_id AS "PM_USER_ID",
      (SELECT user_name FROM user_info WHERE user_id = CM.pm_user_id LIMIT 1) AS "PM_USER_NAME",
      CM.contract_currency AS "CONTRACT_CURRENCY",
      (SELECT code_name FROM comm_code WHERE code_id = CM.contract_currency LIMIT 1) AS "CONTRACT_CURRENCY_NAME",
      CM.contract_price_currency AS "CONTRACT_PRICE_CURRENCY",
      CM.contract_price AS "CONTRACT_PRICE",
      CM.project_name AS "PROJECT_NAME",
      CM.contract_del_date AS "CONTRACT_DEL_DATE",
      CM.req_del_date AS "REQ_DEL_DATE",
      CM.contract_company AS "CONTRACT_COMPANY",
      (SELECT code_name FROM comm_code WHERE code_id = CM.contract_company LIMIT 1) AS "CONTRACT_COMPANY_NAME",
      CM.manufacture_plant AS "MANUFACTURE_PLANT",
      (SELECT code_name FROM comm_code WHERE code_id = CM.manufacture_plant LIMIT 1) AS "MANUFACTURE_PLANT_NAME"
    FROM contract_mgmt CM
    WHERE ${where}
    ORDER BY CM.regdate DESC
  `;

  const rows = await queryRows(sql, params);
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
