import { NextRequest, NextResponse } from "next/server";
import { stripe } from "@/lib/stripe";
import Stripe from "stripe";

// In production, use STRIPE_WEBHOOK_SECRET to verify webhook signatures
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET || "";

export async function POST(request: NextRequest) {
  try {
    const body = await request.text();
    const signature = request.headers.get("stripe-signature") || "";

    let event: Stripe.Event;

    // Verify webhook signature in production
    if (webhookSecret && webhookSecret !== "whsec_...") {
      try {
        event = stripe.webhooks.constructEvent(body, signature, webhookSecret);
      } catch (err) {
        console.error("Webhook signature verification failed:", err);
        return NextResponse.json({ error: "Invalid signature" }, { status: 400 });
      }
    } else {
      // Dev mode: parse without verification
      event = JSON.parse(body) as Stripe.Event;
    }

    // Handle different event types
    switch (event.type) {
      case "checkout.session.completed": {
        const session = event.data.object as Stripe.Checkout.Session;
        console.log("[Stripe] Checkout completed:", session.id);

        // In production:
        // 1. Get customer ID from session
        // 2. Find user by stripe_customer_id
        // 3. Update subscription status to 'active'
        // await supabaseAdmin.from('subscriptions').update({
        //   stripe_subscription_id: session.subscription,
        //   status: 'active',
        //   current_period_start: new Date().toISOString(),
        // }).eq('stripe_customer_id', session.customer);
        break;
      }

      case "customer.subscription.updated": {
        const subscription = event.data.object as Stripe.Subscription;
        console.log("[Stripe] Subscription updated:", subscription.id);

        // In production:
        // await supabaseAdmin.from('subscriptions').update({
        //   status: subscription.status,
        //   current_period_end: new Date(subscription.current_period_end * 1000).toISOString(),
        //   cancel_at_period_end: subscription.cancel_at_period_end,
        // }).eq('stripe_subscription_id', subscription.id);
        break;
      }

      case "customer.subscription.deleted": {
        const subscription = event.data.object as Stripe.Subscription;
        console.log("[Stripe] Subscription canceled:", subscription.id);

        // In production:
        // await supabaseAdmin.from('subscriptions').update({
        //   status: 'canceled',
        // }).eq('stripe_subscription_id', subscription.id);
        break;
      }

      case "invoice.payment_failed": {
        const invoice = event.data.object as Stripe.Invoice;
        console.log("[Stripe] Payment failed:", invoice.id);

        // In production:
        // Mark subscription as past_due
        // Send notification to user
        break;
      }

      default:
        console.log(`[Stripe] Unhandled event type: ${event.type}`);
    }

    return NextResponse.json({ received: true });
  } catch (error) {
    console.error("Stripe webhook error:", error);
    return NextResponse.json(
      { error: "Webhook processing failed" },
      { status: 500 }
    );
  }
}
