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

// 자재이동 저장 (saveInventoryMove 대응)
// 원본: InventoryMngController.saveInventoryMove → mergeInventoryMoveInfo + saveInventoryMoveInInfo
// 각 라인별로:
//   1) 기존 inventory_mgmt_in 행의 move_objid=신규OBJID, move_qty=이동수량 업데이트
//   2) 신규 inventory_mgmt_in 행 INSERT (이동된 재고, move_date/move_user 포함)
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.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) {
      const moveObjId = createObjectId();

      // 1. 원본 inventory_mgmt_in 행의 move_objid/move_qty 갱신
      await client.query(
        `UPDATE inventory_mgmt_in
           SET move_objid = $1::varchar,
               move_qty = $2
         WHERE objid = $3`,
        [moveObjId, line.MOVE_QTY, line.IN_OBJID],
      );

      // 2. 신규 inventory_mgmt_in 행 INSERT (같은 parent_objid 아래 이동처리된 행)
      // $1은 새 inventory_mgmt_in.objid + 원본 행 검색용 move_objid로 두 번 사용 → 명시 cast
      await client.query(
        `INSERT INTO inventory_mgmt_in (
            objid, parent_objid, receipt_qty, location, sub_location,
            writer, regdate, purchase_order_master_objid, contract_mgmt_objid,
            purchase_order_sub_objid, move_date, move_user
         )
         SELECT $1::varchar, parent_objid, $2, $3, $4, $5, now(),
                purchase_order_master_objid, contract_mgmt_objid, purchase_order_sub_objid,
                $6, $7
           FROM inventory_mgmt_in
          WHERE move_objid = $8::varchar`,
        [
          moveObjId,
          line.MOVE_QTY,
          line.LOCATION || "",
          line.SUB_LOCATION || "",
          user.userId,
          line.MOVE_DATE || "",
          line.MOVE_USER || "",
          moveObjId,
        ],
      );
    }

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