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

// 자재불출 완료 (acceptInventoryRequestInfo 대응)
// 원본: InventoryMngController.acceptInventoryRequestInfo, inventoryMng.xml line 2191, 2200, 2073
// 1) transfer(인계) 라인별 OUT_QTY/OUT_DATE/ACQ_USER 업데이트 (lines 파라미터 활용)
// 2) mergeAcceptInventoryRequestInfo: master의 outstatus='complete', request_date 업데이트
// 3) mergeAcceptInventoryRequestPartInfo: 모든 OUT 라인의 out_date 일괄 업데이트
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 masterObjId = String(body.INVENTORY_REQUEST_MASTER_OBJID || "");
  if (!masterObjId) {
    return NextResponse.json({ success: false, message: "마스터 OBJID 누락" }, { status: 400 });
  }
  const lines: Array<Record<string, unknown>> = Array.isArray(body.lines) ? body.lines : [];
  const requestDate = String(body.REQUEST_DATE || getDate());

  const client = await pool.connect();
  try {
    await client.query("BEGIN");

    // 1. 라인별 OUT_QTY/OUT_DATE/ACQ_USER 업데이트
    for (const line of lines) {
      await client.query(
        `INSERT INTO inventory_mgmt_out
            (objid, parent_objid, request_qty, writer, regdate,
             inventory_request_master_objid)
         VALUES ($1, $2, $3, $4, NOW(), $5)
         ON CONFLICT (objid) DO UPDATE SET
           out_qty = $6,
           out_date = $7,
           acq_user = $8,
           writer = $4`,
        [
          String(line.OBJID || ""),
          String(line.PARENT_OBJID || ""),
          String(line.REQUEST_QTY || "0"),
          user.userId,
          masterObjId,
          String(line.OUT_QTY || "0"),
          String(line.OUT_DATE || requestDate),
          String(line.ACQ_USER || ""),
        ],
      );
    }

    // 2. 마스터 불출완료 상태
    await client.query(
      `UPDATE inventory_mgmt_out_master
          SET outstatus = $1,
              request_date = $2
        WHERE objid = $3`,
      ["complete", requestDate, masterObjId],
    );

    // 3. 상세 out_date 일괄
    await client.query(
      `UPDATE inventory_mgmt_out
          SET out_date = $1
        WHERE inventory_request_master_objid = $2`,
      [requestDate, masterObjId],
    );

    await client.query("COMMIT");
    return NextResponse.json({ success: true, message: "불출완료되었습니다." });
  } catch (e) {
    await client.query("ROLLBACK");
    console.error("inventory request accept:", e);
    return NextResponse.json(
      { success: false, message: "오류가 발생하였습니다." },
      { status: 500 },
    );
  } finally {
    client.release();
  }
}
