// Stripe subscription webhook.
//
// Subscribes to checkout + subscription lifecycle events and mirrors them
// into the `subscriptions` table. Tested events:
//   - checkout.session.completed
//   - customer.subscription.created / updated / deleted
//
// Set STRIPE_WEBHOOK_SECRET in .env.local. In `stripe listen --forward-to
// localhost:3000/api/webhooks/stripe` during dev. In production register
// at https://dashboard.stripe.com → Developers → Webhooks.

import Stripe from 'stripe';
import { NextResponse } from 'next/server';
import { headers } from 'next/headers';
import { getServiceSupabase } from '@/lib/db';
import { getStripe } from '@/lib/stripe';

export async function POST(req: Request) {
  const secret = process.env.STRIPE_WEBHOOK_SECRET;
  if (!secret) return NextResponse.json({ error: 'webhook_secret_missing' }, { status: 500 });

  const payload = await req.text();
  const sig = (await headers()).get('stripe-signature');
  if (!sig) return NextResponse.json({ error: 'signature_missing' }, { status: 400 });

  let event: Stripe.Event;
  try {
    event = getStripe().webhooks.constructEvent(payload, sig, secret);
  } catch (err) {
    return NextResponse.json({ error: 'signature_invalid', detail: err instanceof Error ? err.message : String(err) }, { status: 400 });
  }

  const supabase = getServiceSupabase();

  if (event.type === 'customer.subscription.created' || event.type === 'customer.subscription.updated') {
    const sub = event.data.object as Stripe.Subscription;
    await supabase.from('subscriptions').upsert({
      stripe_subscription_id: sub.id,
      stripe_customer_id: typeof sub.customer === 'string' ? sub.customer : sub.customer.id,
      status: sub.status,
      price_id: sub.items.data[0]?.price.id ?? null,
      current_period_end: new Date(sub.current_period_end * 1000).toISOString(),
    }, { onConflict: 'stripe_subscription_id' });
  } else if (event.type === 'customer.subscription.deleted') {
    const sub = event.data.object as Stripe.Subscription;
    await supabase
      .from('subscriptions')
      .update({ status: 'canceled', canceled_at: new Date().toISOString() })
      .eq('stripe_subscription_id', sub.id);
  }

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