import { Request, Response, NextFunction } from 'express';
import { defineAbilitiesFor, getAnalyticsLevel } from '../config/abilities';
import { UniResponse } from '../lib/UniResponse';
import { ForbiddenError } from '@casl/ability';
import { humanizeClientError } from '../utils/humanReadableError';
import UserModel from '../models/User';
import { getTierConfig } from '../config/subscriptionTiers';

/**
 * Extended Request interface to include user and ability information
 */
interface AuthenticatedRequest extends Request {
  user?: {
    userId: string;
    email: string;
    role: string;
  };
  ability?: ReturnType<typeof defineAbilitiesFor>;
}

/**
 * Middleware factory to check if user has access to a specific feature
 *
 * @param feature - The feature to check access for
 * @param action - The action to perform (default: 'access')
 * @returns Express middleware function
 *
 * @example
 * // Check if user can access advanced analytics
 * router.get('/analytics/advanced', authenticateToken, checkFeatureAccess('Analytics', 'access', { level: 'advanced' }), getAdvancedAnalytics);
 *
 * // Check if user can manage custom branding
 * router.put('/branding', authenticateToken, checkFeatureAccess('CustomBranding', 'manage'), updateBranding);
 *
 * // Check if user has HIPAA compliance
 * router.post('/hipaa-data', authenticateToken, checkFeatureAccess('HIPAACompliance', 'access'), createHIPAAData);
 */
export function checkFeatureAccess(
  feature:
    | 'Analytics'
    | 'CustomBranding'
    | 'HIPAACompliance'
    | 'API'
    | 'PrioritySupport',
  action: 'access' | 'manage' = 'access',
  conditions?: any
) {
  return async (
    req: AuthenticatedRequest,
    res: Response,
    next: NextFunction
  ): Promise<void> => {
    try {
      const userId = req.user?.userId;

      // Step 1: Verify user authentication
      if (!userId) {
        res.status(401).json(UniResponse.Error('User not authenticated', null, 401));
        return;
      }

      // Step 2: Get user's subscription tier
      const user = await UserModel.findById(userId).select('subscription_tier');
      if (!user) {
        res.status(404).json(UniResponse.Error('User not found', null, 404));
        return;
      }

      const subscriptionTier = user.subscription_tier || 'free';

      // Step 3: Define CASL abilities for the user
      const ability = defineAbilitiesFor({
        subscription_tier: subscriptionTier,
        userId,
      });
      req.ability = ability;

      // Step 4: Check CASL permissions
      try {
        ForbiddenError.from(ability).throwUnlessCan(action, feature, conditions);
      } catch (error: any) {
        const tierConfig = getTierConfig(subscriptionTier);
        const featureMessages: Record<string, string> = {
          Analytics: `Advanced analytics are not available on your current plan. Please upgrade to Professional plan.`,
          CustomBranding: `Custom branding is not available on your current plan. Please upgrade to Personal or Professional plan.`,
          HIPAACompliance: `HIPAA compliance features are not available on your current plan. Please upgrade to Professional plan.`,
          API: `API access is not available on your current plan. Please upgrade to Professional plan.`,
          PrioritySupport: `Priority support is not available on your current plan. Please upgrade to Professional plan.`,
        };

        res.status(403).json(
          UniResponse.Error(
            humanizeClientError(
              error,
              featureMessages[feature] ||
                'This feature is not available on your current plan.'
            ),
            {
              subscription_tier: subscriptionTier,
              feature,
              upgrade_required: true,
              current_plan: tierConfig.name,
            },
            403
          )
        );
        return;
      }

      // Step 5: User has access, proceed to next middleware
      next();
    } catch (error) {
      console.error(`Error in checkFeatureAccess middleware for ${feature}:`, error);
      res
        .status(500)
        .json(UniResponse.Error('Failed to check feature access', null, 500));
    }
  };
}

/**
 * Middleware to check analytics level access
 * Allows filtering analytics data based on subscription tier
 *
 * @example
 * router.get('/analytics', authenticateToken, checkAnalyticsAccess, getAnalytics);
 */
export const checkAnalyticsAccess = async (
  req: AuthenticatedRequest,
  res: Response,
  next: NextFunction
): Promise<void> => {
  try {
    const userId = req.user?.userId;

    if (!userId) {
      res.status(401).json(UniResponse.Error('User not authenticated', null, 401));
      return;
    }

    const user = await UserModel.findById(userId).select('subscription_tier');
    if (!user) {
      res.status(404).json(UniResponse.Error('User not found', null, 404));
      return;
    }

    const subscriptionTier = user.subscription_tier || 'free';
    const analyticsLevel = getAnalyticsLevel(subscriptionTier);

    // Attach analytics level to request for use in controller
    (req as any).analyticsLevel = analyticsLevel;

    next();
  } catch (error) {
    console.error('Error in checkAnalyticsAccess middleware:', error);
    res
      .status(500)
      .json(UniResponse.Error('Failed to check analytics access', null, 500));
  }
};

/**
 * Middleware to check custom branding access
 *
 * @example
 * router.put('/qrcode/:id/branding', authenticateToken, checkCustomBrandingAccess, updateQRCodeBranding);
 */
export const checkCustomBrandingAccess = checkFeatureAccess('CustomBranding', 'manage');

/**
 * Middleware to check HIPAA compliance access
 *
 * @example
 * router.post('/qrcode/hipaa', authenticateToken, checkHIPAAAccess, createHIPAAQRCode);
 */
export const checkHIPAAAccess = checkFeatureAccess('HIPAACompliance', 'access');

/**
 * Middleware to check API access
 *
 * @example
 * router.get('/api/v1/data', authenticateToken, checkAPIAccess, getAPIData);
 */
export const checkAPIAccess = checkFeatureAccess('API', 'access');

/**
 * Middleware to check priority support access
 *
 * @example
 * router.post('/support/priority', authenticateToken, checkPrioritySupportAccess, createPriorityTicket);
 */
export const checkPrioritySupportAccess = checkFeatureAccess(
  'PrioritySupport',
  'access'
);
