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

// 공급업체 + 담당자 저장 (원본: admin/saveSupMgmtInfo.do)
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 {
    await client.query("BEGIN");

    if (isNew) {
      await client.query(
        `INSERT INTO admin_supply_mng
          (objid, supply_code, supply_name, area_cd, charge_user_name,
           bus_reg_no, reg_no, supply_busname, supply_stockname, supply_address,
           supply_tel_no, email, office_no, supply_fax_no,
           reg_id, reg_date, status)
         VALUES ($1::numeric, $2,$3,$4,$5, $6,$7,$8,$9,$10, $11,$12,$13,$14,
                 $15, now(), 'active')`,
        [
          objid,
          body.supply_code || "",
          body.supply_name || "",
          body.area_cd || "",
          body.charge_user_name || "",
          body.bus_reg_no || "",
          body.reg_no || "",
          body.supply_busname || "",
          body.supply_stockname || "",
          body.supply_address || "",
          body.supply_tel_no || "",
          body.email || "",
          body.office_no || "",
          body.supply_fax_no || "",
          user.userId,
        ]
      );
    } else {
      await client.query(
        `UPDATE admin_supply_mng SET
           supply_code = $2,
           supply_name = $3,
           area_cd = $4,
           charge_user_name = $5,
           bus_reg_no = $6,
           reg_no = $7,
           supply_busname = $8,
           supply_stockname = $9,
           supply_address = $10,
           supply_tel_no = $11,
           email = $12,
           office_no = $13,
           supply_fax_no = $14
         WHERE objid::text = $1`,
        [
          objid,
          body.supply_code || "",
          body.supply_name || "",
          body.area_cd || "",
          body.charge_user_name || "",
          body.bus_reg_no || "",
          body.reg_no || "",
          body.supply_busname || "",
          body.supply_stockname || "",
          body.supply_address || "",
          body.supply_tel_no || "",
          body.email || "",
          body.office_no || "",
          body.supply_fax_no || "",
        ]
      );
    }

    // 담당자 전체 재작성 (원본과 동일하게 supply_objid 기준 delete + insert)
    await client.query(`DELETE FROM supply_charger_mng WHERE supply_objid = $1`, [objid]);
    type Charger = {
      charger_type?: string;
      charger_name?: string;
      phone?: string;
      tel?: string;
      fax?: string;
      email?: string;
    };
    const chargers: Charger[] = Array.isArray(body.chargers) ? body.chargers : [];
    for (const c of chargers) {
      if (!c.charger_name && !c.charger_type && !c.phone && !c.tel && !c.email) continue;
      await client.query(
        `INSERT INTO supply_charger_mng
           (objid, supply_objid, charger_type, charger_name, phone, tel, fax, email, writer, regdate)
         VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now())`,
        [
          createObjectId(),
          objid,
          c.charger_type || "",
          c.charger_name || "",
          c.phone || "",
          c.tel || "",
          c.fax || "",
          c.email || "",
          user.userId,
        ]
      );
    }

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