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

// 자재등록 (saveinventoryForm 대응)
// 원본 쿼리: inventoryMng.xml line 595
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 = body.objId || body.objid || createObjectId();

  try {
    // inventory_mgmt PK = (contract_objid, unit, part_objid) 복합키
    await execute(
      `INSERT INTO inventory_mgmt
        (objid, contract_objid, unit, part_objid, cls_cd, cau_cd, qty,
         location, sub_location, reg_date, price, writer)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
       ON CONFLICT (contract_objid, unit, part_objid) DO UPDATE SET
         cls_cd = EXCLUDED.cls_cd,
         cau_cd = EXCLUDED.cau_cd,
         qty = EXCLUDED.qty,
         location = EXCLUDED.location,
         sub_location = EXCLUDED.sub_location,
         price = EXCLUDED.price,
         writer = EXCLUDED.writer`,
      [
        objId,
        body.contract_objid || body.project_no || "",
        body.unit || "",
        body.part_objid || body.part_no || "",
        body.cls_cd || "",
        body.cau_cd || "",
        body.qty || "0",
        body.location || "",
        body.sub_location || "",
        body.reg_date || getDate(),
        body.price || "0",
        user.userId,
      ],
    );
    return NextResponse.json({ success: true, message: "저장되었습니다." });
  } catch (e) {
    console.error("inventory list save:", e);
    return NextResponse.json({ success: false, message: "오류가 발생하였습니다." }, { status: 500 });
  }
}
