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


// Stub — Stripe credentials will be added later
export async function POST(request: NextRequest) {
  const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET_RMP;
  if (!webhookSecret) {
    return NextResponse.json({ error: 'Stripe not configured' }, { status: 503 });
  }

  // TODO: Verify Stripe webhook signature when STRIPE_WEBHOOK_SECRET_RMP is set
  // const sig = request.headers.get('stripe-signature');
  // const event = stripe.webhooks.constructEvent(body, sig, webhookSecret);

  const body = await request.json();
  const eventType = body?.type;

  if (eventType === 'payment_intent.succeeded') {
    const supabase = await createClient();
    const stripeId = body?.data?.object?.id;
    const amountCents = body?.data?.object?.amount;

    if (stripeId && amountCents) {
      const { data: invoice } = await supabase
        .from('rmp_invoices')
        .select('id')
        .eq('amount_cents', amountCents)
        .eq('status', 'pending')
        .limit(1)
        .single();

      if (invoice) {
        await supabase.from('rmp_invoices').update({
          status: 'paid',
          payment_method: 'stripe',
          stripe_payment_id: stripeId,
          paid_date: new Date().toISOString().split('T')[0],
        }).eq('id', invoice.id);

        await supabase.from('rmp_notifications').insert({
          type: 'stripe_payment',
          message: `Stripe payment received: ${stripeId}`,
          invoice_id: invoice.id,
        });
      }
    }
  }

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