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

// 불출의뢰서 인계 저장 (saveInventoryTransfer 대응)
// 원본: InventoryMngController.saveInventoryTransfer, inventoryMng.xml line 1848
// 각 라인의 OUT_QTY/OUT_DATE/ACQ_USER/WRITER 업데이트
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 lines: Array<Record<string, unknown>> = Array.isArray(body.lines) ? body.lines : [];
  if (lines.length === 0) {
    return NextResponse.json({ success: false, message: "저장할 라인이 없습니다." });
  }

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

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

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