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

// 불출의뢰서 접수 (receiptInventoryRequestInfo / mergeReceiptInventoryRequestInfo 대응)
// 원본: InventoryMngController.receiptInventoryRequestInfo, inventoryMng.xml line 2073
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 checkArr: string[] = Array.isArray(body.checkArr)
    ? body.checkArr.map(String)
    : String(body.checkArr || "")
        .split(",")
        .map((s: string) => s.trim())
        .filter(Boolean);

  if (checkArr.length === 0) {
    return NextResponse.json({ success: false, message: "선택된 데이터가 없습니다." });
  }

  try {
    for (const objId of checkArr) {
      await execute(
        `UPDATE inventory_mgmt_out_master
            SET reception_status = $1,
                reception_date = $2,
                reception_id = $3
          WHERE objid = $4`,
        ["reception", getDate(), user.userId, objId],
      );
    }
    return NextResponse.json({ success: true, message: "접수되었습니다." });
  } catch (e) {
    console.error("inventory request receipt:", e);
    return NextResponse.json(
      { success: false, message: "오류가 발생하였습니다." },
      { status: 500 },
    );
  }
}
