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

// 불출의뢰서 저장 (inventoryMng.saveInventoryRequest + mergeInventoryRequestMasterInfo 대응)
// 원본: inventoryMng.xml line 1781, 1902
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 remark = String(body.REMARK || "");
  const requestDate = String(body.REQUEST_DATE || getDate());
  const lines: Array<Record<string, unknown>> = Array.isArray(body.lines) ? body.lines : [];

  // 첫 라인의 contract_mgmt_objid를 마스터 contract_mgmt_objid로 사용
  const firstContractObjId = String(lines[0]?.CONTRACT_MGMT_OBJID || "");

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

    // 1. inventory_mgmt_out_master UPSERT
    // INVENTORY_OUT_NO 자동 생성: Rfw-YYYY-N (연도별 증가, 패딩 없음 — 원본 FITO 포맷)
    // 원본: request_id와 writer 모두 current user id. $5를 별도 파라미터로 전달해 타입 추론 충돌 회피
    const year = new Date().getFullYear();
    await client.query(
      `INSERT INTO inventory_mgmt_out_master
         (objid, parent_objid, inventory_out_no, request_date, request_id,
          writer, regdate, remark, contract_mgmt_objid)
       VALUES (
         $1, $2,
         (SELECT 'Rfw-' || $3 || '-' ||
            (COALESCE(MAX(CASE WHEN SPLIT_PART(inventory_out_no, '-', 3) = ''
                                    OR inventory_out_no IS NULL
                               THEN 0
                               ELSE SPLIT_PART(inventory_out_no, '-', 3)::numeric
                          END), 0)::integer + 1)::text
          FROM inventory_mgmt_out_master),
         $4, $5, $6, now(), $7, $8
       )
       ON CONFLICT (objid) DO UPDATE SET
         remark = EXCLUDED.remark`,
      [
        masterObjId,
        String(body.PARENT_OBJID || ""),
        String(year),
        requestDate,
        user.userId,
        user.userId,
        remark,
        firstContractObjId,
      ],
    );

    // 2. 기존 파트 삭제 (initInventoryRequestPart)
    await client.query(
      `DELETE FROM inventory_mgmt_out WHERE inventory_request_master_objid = $1`,
      [masterObjId],
    );

    // 3. 라인 INSERT
    for (const line of lines) {
      await client.query(
        `INSERT INTO inventory_mgmt_out
            (objid, parent_objid, request_qty, writer, regdate,
             inventory_request_master_objid, contract_mgmt_objid, unit)
         VALUES ($1, $2, $3, $4, now(), $5, $6, $7)`,
        [
          String(line.OBJID || ""),
          String(line.PARENT_OBJID || ""),
          String(line.REQUEST_QTY || "0"),
          user.userId,
          masterObjId,
          String(line.CONTRACT_MGMT_OBJID || ""),
          String(line.UNIT || ""),
        ],
      );
    }

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