import { NextRequest, NextResponse } from 'next/server';
import { SubscriptionTier, getTierFeatures } from '../config/billing.config';

/**
 * Middleware to check if user has access to required tier features
 */
export function requireTier(
  request: NextRequest,
  requiredTier: SubscriptionTier
): NextResponse | null {
  const userTier = request.headers.get('x-user-tier') as SubscriptionTier;

  if (!userTier) {
    return NextResponse.json({ error: 'User tier not found' }, { status: 401 });
  }

  const tierOrder: Record<SubscriptionTier, number> = {
    [SubscriptionTier.BASIC]: 1,
    [SubscriptionTier.PLUS]: 2,
    [SubscriptionTier.PREMIUM]: 3,
  };

  if (tierOrder[userTier] < tierOrder[requiredTier]) {
    return NextResponse.json(
      {
        error: `Feature requires ${requiredTier} tier or higher`,
        currentTier: userTier,
        requiredTier,
      },
      { status: 403 }
    );
  }

  return null;
}

/**
 * Middleware to check feature limits
 */
export function checkFeatureLimit(
  request: NextRequest,
  feature: string,
  currentValue: number
): NextResponse | null {
  const userTier = request.headers.get('x-user-tier') as SubscriptionTier;

  if (!userTier) {
    return null;
  }

  const features = getTierFeatures(userTier);
  const featureLimit = features[feature as keyof typeof features] as number;

  if (currentValue > featureLimit) {
    return NextResponse.json(
      {
        error: `Feature limit exceeded`,
        feature,
        current: currentValue,
        limit: featureLimit,
        tier: userTier,
      },
      { status: 400 }
    );
  }

  return null;
}
