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

// 원본: /salesMng/receiptSalesPartChgInfo.do
// 선택된 설계변경 이력(part_mng_history) 각 행마다 sales_part_chg UPSERT with ACT_STATUS='0001064' (접수)
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const { rows } = await request.json();
  if (!Array.isArray(rows) || rows.length === 0) {
    return NextResponse.json({ success: false, message: "접수할 항목을 선택하세요." });
  }

  const today = new Date().toISOString().slice(0, 10);
  const client = await pool.connect();
  try {
    await client.query("BEGIN");

    for (const row of rows) {
      const partObjId = String(row.OBJID || "");
      if (!partObjId) continue;

      // 기존 SPC가 있으면 ACT_STATUS만 업데이트, 없으면 신규 INSERT
      const existing = await client.query(
        `SELECT objid FROM sales_part_chg WHERE part_objid = $1 AND COALESCE(qty_child_objid,'') = COALESCE($2,'') LIMIT 1`,
        [partObjId, String(row.QTY_CHILD_OBJID || "")]
      );

      if (existing.rowCount && existing.rowCount > 0) {
        await client.query(
          `UPDATE sales_part_chg
             SET act_status = '0001064',
                 confirm_date = $1,
                 writer = $2,
                 regdate = now()
           WHERE objid = $3`,
          [today, user.userId, existing.rows[0].objid]
        );
      } else {
        await client.query(
          `INSERT INTO sales_part_chg (
             objid, part_objid, confirm_date, act_status,
             bom_report_objid, qty_child_objid, writer, regdate
           ) VALUES ($1, $2, $3, '0001064', $4, $5, $6, now())`,
          [
            createObjectId(),
            partObjId,
            today,
            String(row.BOM_REPORT_OBJID || ""),
            String(row.QTY_CHILD_OBJID || ""),
            user.userId,
          ]
        );
      }
    }

    await client.query("COMMIT");
    return NextResponse.json({ success: true, message: `${rows.length}건 접수되었습니다.` });
  } catch (e) {
    await client.query("ROLLBACK");
    console.error("design-change receipt:", e);
    return NextResponse.json({ success: false, message: "접수 중 오류가 발생했습니다." }, { status: 500 });
  } finally {
    client.release();
  }
}
