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 isNew = !body.objId || body.actionType === "regist";
  const objId = isNew ? createObjectId() : body.objId;

  const client = await pool.connect();
  try {
    await client.query(
      `INSERT INTO invoice_mgmt (objid, parent_objid, group_seq, price_sum, issuance_date, status, regdate, writer)
       VALUES ($1, $2, $3, $4, $5, $6, now(), $7)
       ON CONFLICT (objid) DO UPDATE SET
        parent_objid=EXCLUDED.parent_objid,
        group_seq=EXCLUDED.group_seq,
        price_sum=EXCLUDED.price_sum,
        issuance_date=EXCLUDED.issuance_date,
        status=EXCLUDED.status`,
      [objId, body.parent_objid || "", body.group_seq || 1,
       body.price_sum || body.supply_amount || "0",
       body.issuance_date || null, body.status || "created", user.userId]
    );
    return NextResponse.json({ success: true, objId, message: isNew ? "등록되었습니다." : "수정되었습니다." });
  } catch (e) {
    console.error("Invoice save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  } finally { client.release(); }
}
