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

// 조립 저장 (UPSERT to assembly_wbs_task)
// body: { parentObjid (part_bom_report.objid), rows: [{ ASSEMBLY_OBJID?, PART_OBJID, CHILD_OBJID, ASSEMBLY_USER_ID, ASSEMBLY_DATE, INSOURCING, OUTSOURCING }] }
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 parentObjid = String(body.parentObjid || "");
  const rows: Array<Record<string, unknown>> = Array.isArray(body.rows) ? body.rows : [];
  if (!parentObjid) return NextResponse.json({ success: false, message: "parentObjid 누락" }, { status: 400 });

  try {
    for (const r of rows) {
      const partObjid = String(r.PART_OBJID || "");
      const childObjid = String(r.CHILD_OBJID || "");
      const existingObjid = String(r.ASSEMBLY_OBJID || "");
      const userId = String(r.ASSEMBLY_USER_ID || "");
      const date = String(r.ASSEMBLY_DATE || "");
      const insourcing = String(r.INSOURCING || "");
      const outsourcing = String(r.OUTSOURCING || "");

      if (!partObjid) continue;

      if (existingObjid) {
        await execute(
          `UPDATE assembly_wbs_task SET
             assembly_user_id = $1, assembly_date = $2,
             insourcing = $3, outsourcing = $4
           WHERE objid = $5`,
          [userId, date, insourcing, outsourcing, existingObjid],
        );
      } else {
        // 기존 레코드 재확인 (race condition 대비)
        const existing = await queryOne<{ OBJID: string }>(
          `SELECT objid AS "OBJID" FROM assembly_wbs_task
            WHERE parent_objid = $1 AND part_objid = $2 AND bom_qty_child_objid = $3
            LIMIT 1`,
          [parentObjid, partObjid, childObjid],
        );
        if (existing) {
          await execute(
            `UPDATE assembly_wbs_task SET
               assembly_user_id = $1, assembly_date = $2,
               insourcing = $3, outsourcing = $4
             WHERE objid = $5`,
            [userId, date, insourcing, outsourcing, existing.OBJID],
          );
        } else {
          await execute(
            `INSERT INTO assembly_wbs_task
               (objid, parent_objid, part_objid, bom_qty_child_objid,
                assembly_user_id, assembly_date, insourcing, outsourcing)
             VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
            [createObjectId(), parentObjid, partObjid, childObjid, userId, date, insourcing, outsourcing],
          );
        }
      }
    }
    return NextResponse.json({ success: true, message: "저장되었습니다." });
  } catch (e) {
    console.error("assembly save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  }
}
