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

// 고객 상세 (원본: contractMgmt.xml getSupMngInfo)
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 objid = String(body.objid || body.objId || "");
  if (!objid) return NextResponse.json({ success: false, message: "objid 누락" }, { status: 400 });

  const info = await queryOne(
    `SELECT objid::text AS "OBJID",
      cus_no AS "CUS_NO",
      supply_code AS "SUPPLY_CODE",
      supply_name AS "SUPPLY_NAME",
      reg_no AS "REG_NO",
      REGEXP_REPLACE(COALESCE(reg_no,''), '([0-9]{7})', '*******') AS "REG_NO2",
      supply_address AS "SUPPLY_ADDRESS",
      supply_busname AS "SUPPLY_BUSNAME",
      supply_stockname AS "SUPPLY_STOCKNAME",
      supply_tel_no AS "SUPPLY_TEL_NO",
      supply_fax_no AS "SUPPLY_FAX_NO",
      charge_user_name AS "CHARGE_USER_NAME",
      payment_method AS "PAYMENT_METHOD",
      reg_id AS "REG_ID",
      TO_CHAR(reg_date,'YYYY-MM-DD') AS "REGDATE",
      COALESCE(status,'active') AS "STATUS",
      area_cd AS "AREA_CD",
      bus_reg_no AS "BUS_REG_NO",
      office_no AS "OFFICE_NO",
      email AS "EMAIL"
    FROM supply_mng WHERE objid::text = $1`,
    [objid]
  );

  if (!info) return NextResponse.json({ success: false, message: "데이터를 찾을 수 없습니다." });
  return NextResponse.json({ success: true, data: info });
}
