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.actionType === "regist" || !body.objId;
  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, 1, $3, $4, 'created', now(), $5)
       ON CONFLICT (objid) DO UPDATE SET
        parent_objid=EXCLUDED.parent_objid,
        price_sum=EXCLUDED.price_sum,
        issuance_date=EXCLUDED.issuance_date`,
      [objId, body.parent_objid || "", body.price_sum || "", body.issuance_date || null, user.userId]
    );
    return NextResponse.json({ success: true, message: isNew ? "등록되었습니다." : "수정되었습니다." });
  } catch (e) {
    console.error("SCM payment save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." });
  } finally { client.release(); }
}
