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

// 영업관리 > 고객관리 목록 (원본: contractMgmt.xml supplyMngGridPagingList)
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.supply_name) {
    conditions.push(`UPPER(S.supply_name) LIKE UPPER('%' || $${idx++} || '%')`);
    params.push(body.supply_name);
  }
  if (body.supply_code) {
    conditions.push(`S.supply_code = $${idx++}`);
    params.push(body.supply_code);
  }
  if (body.area_cd) {
    conditions.push(`S.area_cd = $${idx++}`);
    params.push(body.area_cd);
  }
  if (body.searchStatus) {
    conditions.push(`UPPER(COALESCE(S.status,'active')) = UPPER($${idx++})`);
    params.push(body.searchStatus);
  }

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

  const sql = `
    SELECT S.objid::text AS "OBJID",
      S.cus_no AS "CUS_NO",
      S.supply_code AS "SUPPLY_CODE",
      (SELECT code_name FROM comm_code WHERE code_id = S.supply_code LIMIT 1) AS "SUPPLY_CODE_NAME",
      S.area_cd AS "AREA_CD",
      (SELECT code_name FROM comm_code WHERE code_id = S.area_cd LIMIT 1) AS "AREA_CD_NAME",
      S.supply_name AS "SUPPLY_NAME",
      S.charge_user_name AS "CHARGE_USER_NAME",
      S.bus_reg_no AS "BUS_REG_NO",
      S.supply_address AS "SUPPLY_ADDRESS",
      S.supply_tel_no AS "SUPPLY_TEL_NO",
      S.email AS "EMAIL",
      TO_CHAR(S.reg_date,'YYYY-MM-DD') AS "REGDATE",
      COALESCE(S.status,'active') AS "STATUS"
    FROM supply_mng S
    WHERE ${where}
    ORDER BY S.cus_no DESC NULLS LAST, S.reg_date DESC
  `;

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