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

// 고객 등록/수정 (원본: contractMgmt.xml mergeSupMgmtInfo)
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 isNew = !body.objid;
  const objid = isNew ? createObjectId() : String(body.objid);

  const client = await pool.connect();
  try {
    if (isNew) {
      // 원본과 동일하게 CUS-XXXX 자동 채번
      await client.query(
        `INSERT INTO supply_mng
          (objid, supply_code, supply_name, reg_no, supply_address, supply_busname,
           supply_stockname, supply_tel_no, supply_fax_no, charge_user_name, payment_method,
           reg_id, reg_date, status, area_cd, bus_reg_no, office_no, email, cus_no)
         VALUES ($1::numeric, $2,$3,$4,$5,$6, $7,$8,$9,$10,$11,
                 $12, now(), 'active', $13,$14,$15,$16,
                 (SELECT 'CUS-' || LPAD((COALESCE(MAX(SUBSTR(cus_no,5,8))::INTEGER,0)+1)::VARCHAR, 4, '0')
                    FROM supply_mng))`,
        [
          objid,
          body.supply_code || "",
          body.supply_name || "",
          body.reg_no || "",
          body.supply_address || "",
          body.supply_busname || "",
          body.supply_stockname || "",
          body.supply_tel_no || "",
          body.supply_fax_no || "",
          body.charge_user_name || "",
          body.payment_method || "",
          body.reg_id || user.userId,
          body.area_cd || "",
          body.bus_reg_no || "",
          body.office_no || "",
          body.email || "",
        ]
      );
    } else {
      await client.query(
        `UPDATE supply_mng SET
           supply_code = $2,
           supply_name = $3,
           reg_no = $4,
           supply_address = $5,
           supply_busname = $6,
           supply_stockname = $7,
           supply_tel_no = $8,
           supply_fax_no = $9,
           charge_user_name = $10,
           payment_method = $11,
           reg_id = $12,
           area_cd = $13,
           bus_reg_no = $14,
           office_no = $15,
           email = $16
         WHERE objid::text = $1`,
        [
          objid,
          body.supply_code || "",
          body.supply_name || "",
          body.reg_no || "",
          body.supply_address || "",
          body.supply_busname || "",
          body.supply_stockname || "",
          body.supply_tel_no || "",
          body.supply_fax_no || "",
          body.charge_user_name || "",
          body.payment_method || "",
          body.reg_id || "",
          body.area_cd || "",
          body.bus_reg_no || "",
          body.office_no || "",
          body.email || "",
        ]
      );
    }

    return NextResponse.json({ success: true, message: isNew ? "등록되었습니다." : "수정되었습니다.", objid });
  } catch (e) {
    console.error("Customer save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  } finally {
    client.release();
  }
}
