import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';

export async function POST(request: NextRequest) {
  const supabase = await createClient();
  const body = await request.json();
  const { invoice_id } = body;

  const notifyEmail = process.env.NOTIFY_EMAIL;
  const notifyPhone = process.env.NOTIFY_PHONE;

  let message = 'Payment received';
  if (invoice_id) {
    const { data: inv } = await supabase.from('rmp_invoices').select('invoice_number, amount_cents').eq('id', invoice_id).single();
    if (inv) message = `Payment received for invoice ${inv.invoice_number}: $${((inv.amount_cents ?? 0) / 100).toFixed(2)}`;
  }

  // Log notification
  await supabase.from('rmp_notifications').insert({ type: 'payment_notify', message, invoice_id: invoice_id ?? null });

  // Email notification (stub — SMTP configured)
  if (notifyEmail) {
    try {
      await fetch(`${process.env.NEXT_PUBLIC_SITE_URL}/api/marketplace/send-email`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ to: notifyEmail, subject: 'RMP Payment Received', text: message }),
      });
    } catch {}
  }

  // SMS via Twilio — stub until credentials added
  if (notifyPhone && process.env.TWILIO_ACCOUNT_SID) {
    // TODO: Add Twilio SMS when credentials are configured
  }

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