import { Request, Response, NextFunction } from 'express';
import { defineAbilitiesFor } from '../config/abilities';
import { UniResponse } from '../lib/UniResponse';
import { ForbiddenError } from '@casl/ability';
import { QRCodeService } from '../controllers/qr-code/qrcodeService';
import { validateStorageUsage, getStorageLimitMB, bytesToMB } from '../config/subscriptionTiers';
import { SubscriptionTier } 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 to check if user can create QR codes based on their subscription tier
 *
 * This middleware:
 * 1. Verifies user authentication
 * 2. Checks CASL abilities for QR code creation
 * 3. Validates subscription limits (e.g., free users can only create 2 QR codes)
 * 4. Provides detailed error messages with upgrade suggestions
 *
 * @example
 * router.post('/qrcodes', authenticateToken, checkQRCodeLimit, createQRCode);
 */
export const checkQRCodeLimit = 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: Check subscription limits using service
    const limitCheck = await QRCodeService.checkQRCodeCreationLimit(userId);

    // Step 3: Define CASL abilities for the user
    // CRITICAL: Must include userId when using conditions in ability rules
    const ability = defineAbilitiesFor({
      subscription_tier: limitCheck.subscriptionTier,
      userId: userId,
    });
    req.ability = ability;

    // Step 4: Check CASL permissions
    try {
      ForbiddenError.from(ability).throwUnlessCan('create', 'QRCode');
    } catch (error) {
      res
        .status(403)
        .json(
          UniResponse.Error('You do not have permission to create QR codes', null, 403)
        );
      return;
    }

    // Step 5: Check storage limits synchronously (before QR code limit check)
    let storageInfo = null;
    let storageExceeded = false;
    let storageError = null;

    try {
      const currentStorageBytes = await QRCodeService.calculateUserStorageUsage(userId);
      const storageValidation = validateStorageUsage(
        limitCheck.subscriptionTier as SubscriptionTier,
        currentStorageBytes,
        0
      );

      const currentStorageMB = storageValidation.currentUsageMB;
      const limitMB = storageValidation.limitMB;
      const remainingMB = storageValidation.remainingMB;

      storageInfo = {
        current_storage_mb: Number(currentStorageMB.toFixed(2)),
        limit_mb: Number(limitMB.toFixed(2)),
        remaining_mb: Number(remainingMB.toFixed(2)),
        current_storage_bytes: currentStorageBytes,
        limit_bytes: Math.round(limitMB * 1024 * 1024),
        remaining_bytes: Math.round(remainingMB * 1024 * 1024),
        is_exceeded: storageValidation.isExceeded,
      };

      storageExceeded = storageValidation.isExceeded;

      if (storageExceeded) {
        const currentGB = (currentStorageMB / 1024).toFixed(2);
        const limitGB = (limitMB / 1024).toFixed(2);
        storageError = `Storage limit exceeded. Current usage: ${currentGB} GB / ${limitGB} GB. Please upgrade your subscription or delete some files to create more QR codes.`;
      }
    } catch (error) {
      console.error('Error calculating storage usage in checkQRCodeLimit:', error);
      // Continue with storage check failure - will still check QR code limits
    }

    // Step 6: Check if user has reached their QR code limit
    const qrCodeLimitReached = !limitCheck.canCreate;
    const limitDisplay =
      limitCheck.limit === Infinity ? 'unlimited' : limitCheck.limit;

    // Step 7: Revoke access if EITHER limit is exceeded
    if (storageExceeded || qrCodeLimitReached) {
      const tierNames = {
        free: 'Free',
        personal: 'Personal',
        family: 'Family',
        professional: 'Professional',
      };

      // Build comprehensive error message
      let errorMessage = '';
      const reasons: string[] = [];

      if (storageExceeded) {
        reasons.push('storage limit exceeded');
        errorMessage += storageError || 'Storage limit exceeded. ';
      }

      if (qrCodeLimitReached) {
        reasons.push('QR code limit reached');
        errorMessage += `Your QR code limit is ${limitDisplay}, and you have ${limitCheck.current} QR codes. `;
      }

      errorMessage += 'Please upgrade your subscription to create more QR codes.';

      // Build comprehensive error response
      const errorResponse: any = {
        current_count: limitCheck.current,
        limit: limitCheck.limit,
        remaining: limitCheck.remaining,
        subscription_tier: limitCheck.subscriptionTier,
        upgrade_required: true,
        access_revoked: true,
        revocation_reasons: reasons,
        description: `Access to create QR codes has been revoked because: ${reasons.join(' and ')}.`,
      };

      // Add storage information if available
      if (storageInfo) {
        errorResponse.storage = storageInfo;
      }

      // Add detailed descriptions
      errorResponse.details = {
        qr_code_limit: {
          reached: qrCodeLimitReached,
          current: limitCheck.current,
          limit: limitCheck.limit,
          remaining: limitCheck.remaining,
          message: qrCodeLimitReached
            ? `You have reached your QR code limit of ${limitDisplay} QR codes.`
            : `You have ${limitCheck.remaining} QR codes remaining.`,
        },
        storage_limit: storageInfo
          ? {
            reached: storageExceeded,
            current_mb: storageInfo.current_storage_mb,
            limit_mb: storageInfo.limit_mb,
            remaining_mb: storageInfo.remaining_mb,
            current_gb: Number((storageInfo.current_storage_mb / 1024).toFixed(2)),
            limit_gb: Number((storageInfo.limit_mb / 1024).toFixed(2)),
            remaining_gb: Number((storageInfo.remaining_mb / 1024).toFixed(2)),
            message: storageExceeded
              ? `You have exceeded your storage limit of ${Number((storageInfo.limit_mb / 1024).toFixed(2))} GB.`
              : `You have ${Number((storageInfo.remaining_mb / 1024).toFixed(2))} GB of storage remaining.`,
          }
          : {
            reached: false,
            message: 'Storage information unavailable.',
          },
      };

      res.status(403).json(
        UniResponse.Error(errorMessage, errorResponse, 403)
      );
      return;
    }

    // Step 8: Both limits are within bounds, user can create QR code
    next();
  } catch (error) {
    console.error('Error in checkQRCodeLimit middleware:', error);
    res
      .status(500)
      .json(UniResponse.Error('Failed to check QR code limits', null, 500));
  }
};
