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

// 검사결과 저장 (assembly_wbs_task.receive_qty 업데이트)
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 client = await pool.connect();
  try {
    // parent_objid(contract)의 assembly_wbs_task들에 receive_qty 업데이트
    if (body.assembly_wbs_objid) {
      await client.query(
        `UPDATE assembly_wbs_task SET
          receive_qty = $1, assembly_date = $2, assembly_user_id = $3
         WHERE objid = $4`,
        [body.receive_qty || "", body.assembly_date || null,
         body.assembly_user_id || user.userId, body.assembly_wbs_objid]
      );
    } else if (body.parent_objid) {
      // 프로젝트 단위 검사 완료 처리 — 신규 assembly_wbs_task 레코드 생성
      const objId = createObjectId();
      await client.query(
        `INSERT INTO assembly_wbs_task (objid, parent_objid, receive_qty,
          assembly_date, assembly_user_id, writer, reg_date)
         VALUES ($1, $2, $3, $4, $5, $6, now())`,
        [objId, body.parent_objid, body.receive_qty || "",
         body.assembly_date || null, body.assembly_user_id || user.userId,
         user.userId]
      );
    }
    return NextResponse.json({ success: true, message: "저장되었습니다." });
  } catch (e) {
    console.error("Inspection save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  } finally { client.release(); }
}
