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

/**
 * Manual sync endpoint to update user subscription from Stripe
 * Use this if the automatic webhook/verify failed
 */
export async function POST(request: NextRequest) {
  try {
    // Use cookie-based auth
    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 all subscriptions for this customer
    const subscriptions = await stripe.subscriptions.list({
      customer: user.stripeCustomerId,
      status: 'active',
      limit: 1,
    });

    if (subscriptions.data.length === 0) {
      // No active subscription - set to FREE
      await db.user.update({
        where: { id: user.id },
        data: {
          stripeSubscriptionId: null,
          stripePriceId: null,
          stripeCurrentPeriodEnd: null,
          plan: 'FREE',
        },
      });

      return NextResponse.json({
        success: true,
        plan: 'FREE',
        message: 'No active subscription found, set to FREE plan',
      });
    }

    const subscription: any = subscriptions.data[0];

    // Determine plan from price ID
    const priceId = subscription.items.data[0]?.price?.id;
    let plan = 'PRO'; // default

    // Check against known price IDs
    if (priceId === process.env.STRIPE_PRICE_ID_BUSINESS_MONTHLY ||
        priceId === process.env.STRIPE_PRICE_ID_BUSINESS_YEARLY) {
      plan = 'BUSINESS';
    } else if (priceId === process.env.STRIPE_PRICE_ID_PRO_MONTHLY ||
               priceId === process.env.STRIPE_PRICE_ID_PRO_YEARLY) {
      plan = 'PRO';
    }

    // Get current_period_end
    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);

    console.log('Syncing subscription:', {
      subscriptionId: subscription.id,
      priceId,
      plan,
      periodEndTimestamp,
      currentPeriodEnd,
    });

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

    return NextResponse.json({
      success: true,
      plan,
      subscriptionId: subscription.id,
      currentPeriodEnd,
    });
  } catch (error) {
    console.error('Error syncing subscription:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
