import { NextRequest, NextResponse } from 'next/server';

import { requireRmpAdmin, markInvoicePaid } from '@/lib/accounting/rmpService';

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const auth = await requireRmpAdmin();
  if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const { id } = await params;
  const body = await request.json();

  const result = await markInvoicePaid(id, body.method, body.paid_date, body.wire_reference, body.stripe_payment_id);

  if (!result.ok) return NextResponse.json({ error: result.error }, { status: 400 });

  // Notify
  try {
    await fetch(`${process.env.NEXT_PUBLIC_SITE_URL}/api/accounting/notify-payment`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ invoice_id: id }),
    });
  } catch {}

  return NextResponse.json({ ok: true });
}
