import { Request, Response, NextFunction } from 'express';
import { defineAbilitiesFor, canCreateScan, getScanLimit } from '../config/abilities';
import { UniResponse } from '../lib/UniResponse';
import { ForbiddenError } from '@casl/ability';
import UserModel from '../models/User';
import ScanModel from '../models/Scan';
import { SubscriptionTier, isValidTier } 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 scans based on their subscription tier
 *
 * This middleware:
 * 1. Verifies user authentication
 * 2. Checks CASL abilities for scan creation
 * 3. Validates subscription limits (e.g., free users limited to 100 scans/month)
 * 4. Provides detailed error messages with upgrade suggestions
 *
 * @example
 * router.post('/scans', authenticateToken, checkScanLimit, createScan);
 */
export const checkScanLimit = 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;
    }

    // Validate and set subscription tier with proper type safety
    const rawTier = user.subscription_tier as string;
    const subscriptionTier: SubscriptionTier = isValidTier(rawTier) ? rawTier : 'free';

    // Step 3: Check if tier has unlimited scans
    const scanLimit = getScanLimit(subscriptionTier);
    if (scanLimit === Infinity) {
      // Unlimited scans, proceed
      next();
      return;
    }

    // Step 4: Count scans in current month
    const now = new Date();
    const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
    const endOfMonth = new Date(
      now.getFullYear(),
      now.getMonth() + 1,
      0,
      23,
      59,
      59,
      999
    );

    const currentMonthScans = await ScanModel.countDocuments({
      scanned_by: userId,
      scanned_at: {
        $gte: startOfMonth,
        $lte: endOfMonth,
      },
    });

    // Step 5: Check if user has reached their scan limit
    const limitCheck = canCreateScan(subscriptionTier, currentMonthScans);

    if (!limitCheck.canScan) {
      const tierNames = {
        free: 'Free',
        personal: 'Personal',
        family: 'Family',
        professional: 'Professional',
      };

      res.status(403).json(
        UniResponse.Error(
          `You have reached your monthly scan limit (${limitCheck.limit} scans) for the ${tierNames[subscriptionTier]} plan. Please upgrade your subscription to scan more QR codes.`,
          {
            current_scans: limitCheck.current,
            limit: limitCheck.limit,
            remaining: limitCheck.remaining,
            subscription_tier: subscriptionTier,
            upgrade_required: true,
            reset_date: endOfMonth,
          },
          403
        )
      );
      return;
    }

    // Step 6: User can create scan, proceed to next middleware
    next();
  } catch (error) {
    console.error('Error in checkScanLimit middleware:', error);
    res.status(500).json(UniResponse.Error('Failed to check scan limits', null, 500));
  }
};
