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

// 원본: /salesMng/saveSalesPartChgInfo.do — sales_part_chg UPSERT
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 spcObjId = String(body.objId || "") || createObjectId();
  const isNew = !body.objId;

  const client = await pool.connect();
  try {
    await client.query(
      `INSERT INTO sales_part_chg (
         objid, part_objid, confirm_date, act_cd,
         purchase_order_master_objid, note, writer, regdate,
         act_status, bom_report_objid, qty_child_objid
       ) VALUES ($1, $2, $3, $4, $5, $6, $7, now(), $8, $9, $10)
       ON CONFLICT (objid) DO UPDATE SET
         part_objid = EXCLUDED.part_objid,
         confirm_date = EXCLUDED.confirm_date,
         act_cd = EXCLUDED.act_cd,
         purchase_order_master_objid = EXCLUDED.purchase_order_master_objid,
         note = EXCLUDED.note,
         writer = EXCLUDED.writer,
         regdate = now(),
         act_status = EXCLUDED.act_status`,
      [
        spcObjId,
        String(body.partObjId || ""),
        String(body.confirm_date || new Date().toISOString().slice(0, 10)),
        String(body.act_cd || ""),
        String(body.purchase_order_master_objid || ""),
        String(body.note || ""),
        user.userId,
        String(body.act_status || "0001064"),
        String(body.bom_report_objid || ""),
        String(body.qty_child_objid || ""),
      ]
    );
    return NextResponse.json({ success: true, objId: spcObjId, message: isNew ? "등록되었습니다." : "수정되었습니다." });
  } catch (e) {
    console.error("design-change save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  } finally {
    client.release();
  }
}
