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

// 거래처/고객사 목록 (원본: common.getsupplyselect → SUPPLY_MNG)
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ RESULTLIST: [] });

  const body = await request.json().catch(() => ({}));
  const conditions: string[] = ["supply_code != '0000269'"];
  const params: unknown[] = [];
  let idx = 1;

  if (body.CHARGER_TYPE) {
    conditions.push(`charger_type = $${idx++}`);
    params.push(body.CHARGER_TYPE);
  }

  const rows = await queryRows(
    `SELECT objid::text AS "OBJID",
       supply_name AS "SUPPLY_NAME",
       supply_code AS "SUPPLY_CODE",
       COALESCE(status, 'A') AS "STATUS"
     FROM supply_mng
     WHERE ${conditions.join(" AND ")}
     ORDER BY supply_name
`,
    params,
  );
  return NextResponse.json({ RESULTLIST: rows });
}
