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

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 = createObjectId();
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    // Insert input record
    await client.query(
      `INSERT INTO inventory_mgmt_in (objid, parent_objid, receipt_qty, location, writer, regdate)
       VALUES ($1, $2, $3, $4, $5, now())`,
      [objId, body.parent_objid || "", body.receipt_qty || "", body.location || "", user.userId]
    );
    // Update parent inventory_mgmt input_qty and input_date
    await client.query(
      `UPDATE inventory_mgmt SET
        input_qty = COALESCE(input_qty, '0')::numeric + COALESCE($1, '0')::numeric || '',
        input_date = now()::text
       WHERE objid = $2`,
      [body.receipt_qty || "0", body.parent_objid || ""]
    );
    await client.query("COMMIT");
    return NextResponse.json({ success: true, message: "입고 등록되었습니다." });
  } catch (e) {
    await client.query("ROLLBACK");
    console.error("Inventory input save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." });
  } finally { client.release(); }
}
