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

// 공급업체관리 목록 조회 (원본: admin.xml getSUPPLYInfoGridList)
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[] = ["COALESCE(S.status,'active') != 'deleted'"];
  const params: unknown[] = [];
  let idx = 1;

  if (body.supply_code) {
    conditions.push(`S.supply_code = $${idx++}`);
    params.push(body.supply_code);
  }
  if (body.supply_name) {
    conditions.push(`UPPER(S.supply_name) LIKE UPPER('%' || $${idx++} || '%')`);
    params.push(body.supply_name);
  }
  if (body.area_cd) {
    conditions.push(`S.area_cd = $${idx++}`);
    params.push(body.area_cd);
  }

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

  const sql = `
    SELECT ROW_NUMBER() OVER (ORDER BY S.reg_date DESC NULLS LAST, S.supply_name)::int AS "RNUM",
      S.objid::text AS "OBJID",
      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.supply_name AS "SUPPLY_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.charge_user_name AS "CHARGE_USER_NAME",
      S.supply_stockname AS "SUPPLY_STOCKNAME",
      S.supply_busname AS "SUPPLY_BUSNAME",
      S.supply_address AS "SUPPLY_ADDRESS",
      S.supply_tel_no AS "SUPPLY_TEL_NO",
      S.supply_fax_no AS "SUPPLY_FAX_NO",
      S.email AS "EMAIL",
      S.bus_reg_no AS "BUS_REG_NO",
      S.reg_no AS "REG_NO",
      S.office_no AS "OFFICE_NO",
      TO_CHAR(S.reg_date,'YYYY-MM-DD') AS "REGDATE",
      COALESCE(S.status,'active') AS "STATUS"
    FROM admin_supply_mng S
    WHERE ${where}
    ORDER BY S.reg_date DESC NULLS LAST, S.supply_name
  `;

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