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

// 구조 수량 저장 (원본: partMng/structureQtySave.do)
// child_objid 기준으로 qty_temp 갱신
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 bomReportObjId = String(body.BOM_REPORT_OBJID || "");
  const childObjId = String(body.CHILD_OBJID || "");
  const qty = String(body.QTY_TEMP ?? body.QTY ?? "");

  if (!childObjId) {
    return NextResponse.json({ success: false, message: "CHILD_OBJID 누락" }, { status: 400 });
  }

  try {
    await execute(
      `UPDATE bom_part_qty SET qty_temp = $1
        WHERE bom_report_objid = $2 AND child_objid = $3`,
      [qty, bomReportObjId, childObjId],
    );
    return NextResponse.json({ success: true, result: true });
  } catch (e) {
    console.error("bom qty save:", e);
    return NextResponse.json({ success: false, message: "저장 실패" }, { status: 500 });
  }
}
