// 입금완료 건 수정 — 입금액/입금일/방법/메모 수정 또는 입금 취소(결재상태 해제)
//   진행상태(status)는 입금과 무관하게 별도이므로 건드리지 않는다.
import { NextRequest, NextResponse } from "next/server";
import { execute, queryOne } from "@/lib/db";
import { requireMomoAdmin } from "@/lib/momo-guard";
import { ensureProcPaymentSeparation } from "@/lib/momo-proc";

export async function POST(req: NextRequest) {
  const g = await requireMomoAdmin();
  if (g instanceof NextResponse) return g;
  await ensureProcPaymentSeparation();

  const body = await req.json().catch(() => ({}));
  const { objid, action, amount, method, memo, paidDate } = body as {
    objid?: string;
    action?: "edit" | "cancel";
    amount?: number; method?: string; memo?: string; paidDate?: string;
  };
  if (!objid) return NextResponse.json({ success: false, message: "objid 필수" }, { status: 400 });

  const proc = await queryOne<{ total_amount: number; paid_date: string | null }>(
    `SELECT total_amount, paid_date FROM momo_procurements WHERE objid::text = $1`,
    [objid]
  );
  if (!proc) return NextResponse.json({ success: false, message: "발주를 찾을 수 없습니다." }, { status: 404 });
  if (!proc.paid_date) {
    return NextResponse.json({ success: false, message: "입금완료 건만 수정할 수 있습니다." }, { status: 400 });
  }

  // 입금 취소 — 결재정보만 제거 (진행상태는 그대로 유지)
  if (action === "cancel") {
    await execute(
      `UPDATE momo_procurements
         SET paid_date = NULL, paid_amount = NULL, paid_method = NULL, paid_memo = NULL
       WHERE objid::text = $1`,
      [objid]
    );
    return NextResponse.json({ success: true });
  }

  // 입금 정보 수정
  const paidAmount = Number(amount) > 0 ? Number(amount) : Number(proc.total_amount);
  await execute(
    `UPDATE momo_procurements
       SET paid_amount = $1,
           paid_method = $2,
           paid_memo   = $3,
           paid_date   = COALESCE($4::timestamp, paid_date)
     WHERE objid::text = $5`,
    [paidAmount, method || null, memo || null, paidDate || null, objid]
  );
  return NextResponse.json({ success: true });
}
