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

// 재고 입고 등록 (saveinventoryForm / insertInventoryIn 대응)
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 objId = body.objId || createObjectId();
  const client = await pool.connect();
  try {
    await client.query("BEGIN");

    // 1. inventory_mgmt 마스터 UPSERT
    await client.query(
      `INSERT INTO inventory_mgmt (objid, contract_objid, unit, part_objid,
        cls_cd, cau_cd, qty, location, sub_location, price, writer, reg_date)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, now())
       ON CONFLICT (contract_objid, unit, part_objid) DO UPDATE SET
        cls_cd=EXCLUDED.cls_cd, cau_cd=EXCLUDED.cau_cd, qty=EXCLUDED.qty,
        location=EXCLUDED.location, sub_location=EXCLUDED.sub_location,
        price=EXCLUDED.price`,
      [objId, body.contract_objid||"", body.unit||"", body.part_objid||"",
       body.cls_cd||"", body.cau_cd||"", body.qty||"0",
       body.location||"", body.sub_location||"", body.price||"0", user.userId]
    );

    // 2. inventory_mgmt_in 트랜잭션 생성 (입고수량 있을 때)
    if (body.receipt_qty && Number(body.receipt_qty) > 0) {
      await client.query(
        `INSERT INTO inventory_mgmt_in (
          objid, parent_objid, receipt_qty, location, sub_location,
          writer, regdate, contract_mgmt_objid
        ) VALUES ($1, $2, $3, $4, $5, $6, now(), $7)`,
        [createObjectId(), objId, String(body.receipt_qty),
         body.location||"", body.sub_location||"", user.userId,
         body.contract_mgmt_objid || body.contract_objid || ""]
      );
    }

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