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

export const dynamic = 'force-dynamic';

export async function GET(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 },
      select: {
        plan: true,
        stripeCurrentPeriodEnd: true,
        stripePriceId: true,
        stripeCustomerId: true,
        stripeSubscriptionId: true,
      },
    });

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

    // Determine billing interval from stripePriceId
    let interval: 'month' | 'year' | null = null;

    if (user.stripePriceId) {
      // Check if the current price ID matches any yearly price ID
      const isYearly =
        user.stripePriceId === STRIPE_PLANS.PRO.priceIdYearly ||
        user.stripePriceId === STRIPE_PLANS.BUSINESS.priceIdYearly;

      interval = isYearly ? 'year' : 'month';
    }

    return NextResponse.json({
      plan: user.plan || 'FREE',
      interval,
      currentPeriodEnd: user.stripeCurrentPeriodEnd,
      priceId: user.stripePriceId,
      stripeCustomerId: user.stripeCustomerId,
      stripeSubscriptionId: user.stripeSubscriptionId,
    });
  } catch (error) {
    console.error('Error fetching user plan:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
