import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { stripe } from '@/lib/stripe';
import { db } from '@/lib/db';

export async function POST(request: NextRequest) {
  try {
    // Use cookie-based auth instead of NextAuth
    const userId = cookies().get('userId')?.value;

    if (!userId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const user = await db.user.findUnique({
      where: { id: userId },
    });

    if (!user) {
      return NextResponse.json({ error: 'User not found' }, { status: 404 });
    }

    if (!user.stripeCustomerId) {
      return NextResponse.json({ error: 'No Stripe customer ID' }, { status: 400 });
    }

    // Get the most recent checkout session for this customer
    const checkoutSessions = await stripe.checkout.sessions.list({
      customer: user.stripeCustomerId,
      limit: 1,
    });

    if (checkoutSessions.data.length === 0) {
      return NextResponse.json({ error: 'No checkout session found' }, { status: 404 });
    }

    const checkoutSession = checkoutSessions.data[0];

    // Only process if payment was successful
    if (checkoutSession.payment_status === 'paid' && checkoutSession.subscription) {
      const subscriptionId = typeof checkoutSession.subscription === 'string'
        ? checkoutSession.subscription
        : checkoutSession.subscription.id;

      // Retrieve the full subscription object
      const subscription: any = await stripe.subscriptions.retrieve(subscriptionId);

      // Determine plan from metadata or price ID
      const plan = checkoutSession.metadata?.plan || 'PRO';

      // Debug log to see the subscription structure
      console.log('Full subscription object:', JSON.stringify(subscription, null, 2));

      // Get current_period_end - Stripe returns it as a Unix timestamp
      // Try different possible field names
      const periodEndTimestamp = subscription.current_period_end
        || subscription.currentPeriodEnd
        || subscription.billing_cycle_anchor;

      const currentPeriodEnd = periodEndTimestamp
        ? new Date(periodEndTimestamp * 1000)
        : new Date(Date.now() + 30 * 24 * 60 * 60 * 1000); // Default to 30 days from now

      console.log('Subscription data:', {
        id: subscription.id,
        periodEndTimestamp,
        currentPeriodEnd,
        priceId: subscription.items?.data?.[0]?.price?.id,
      });

      // Update user in database
      await db.user.update({
        where: { id: user.id },
        data: {
          stripeSubscriptionId: subscription.id,
          stripePriceId: subscription.items.data[0].price.id,
          stripeCurrentPeriodEnd: currentPeriodEnd,
          plan: plan as any,
        },
      });

      return NextResponse.json({
        success: true,
        plan,
        subscriptionId: subscription.id,
      });
    }

    return NextResponse.json({ error: 'Payment not completed' }, { status: 400 });
  } catch (error) {
    console.error('Error verifying session:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
