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

// BOM 저장
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 || body.actionType === "regist";
  const objId = isNew ? createObjectId() : body.objId;

  const client = await pool.connect();
  try {
    await client.query(
      `INSERT INTO bom_part_qty (objid, parent_part_no, part_no, qty, project_no, bom_level, writer, regdate)
       VALUES ($1, $2, $3, $4, $5, $6, $7, now())
       ON CONFLICT (objid) DO UPDATE SET
        parent_part_no=EXCLUDED.parent_part_no, part_no=EXCLUDED.part_no,
        qty=EXCLUDED.qty, project_no=EXCLUDED.project_no, bom_level=EXCLUDED.bom_level`,
      [objId, body.parent_part_no || "", body.part_no || "",
       body.qty || "1", body.project_no || "", body.bom_level || "1", user.userId]
    );
    return NextResponse.json({ success: true, objId, message: isNew ? "등록되었습니다." : "수정되었습니다." });
  } catch (e) {
    console.error("BOM save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  } finally { client.release(); }
}
