import SubscriptionModel from '../models/Subscription';
import UserModel from '../models/User';
import mongoose from 'mongoose';
import { SubscriptionTier, isValidTier } from '../config/subscriptionTiers';
import { humanizeClientError } from './humanReadableError';

export class SubscriptionHelper {
  /**
   * Create or update to free tier subscription
   * ENSURES ONLY ONE SUBSCRIPTION DOCUMENT PER USER
   */
  public static async createFreeSubscription(userId: string | mongoose.Types.ObjectId) {
    try {
      // Check if user already has a subscription
      const existingSubscription = await SubscriptionModel.findOne({
        user_id: userId,
        is_active: true,
      });

      let subscription;

      if (existingSubscription) {
        // Update existing subscription to free tier
        // Use a two-step update to avoid unique index conflicts with sparse indexes
        // Step 1: Update all fields except stripe_subscription_id
        await SubscriptionModel.updateOne(
          { _id: existingSubscription._id },
          {
            $set: {
              tier: 'free',
              product_id: null,
              price_id: null,
              status: 'active',
              current_period_start: new Date(),
              current_period_end: new Date('2099-12-31'), // Free tier never expires
              amount: 0,
              currency: 'usd',
              interval: 'lifetime',
              is_active: true,
              cancel_at_period_end: false,
              canceled_at: null,
              metadata: {
                tier_type: 'free',
                updated_via: 'downgrade_or_cancellation',
                updated_at: new Date().toISOString(),
              },
            },
          }
        );

        // Step 2: Remove stripe_subscription_id field separately to avoid unique index conflict
        try {
          await SubscriptionModel.updateOne(
            { _id: existingSubscription._id },
            {
              $unset: {
                stripe_subscription_id: '', // Remove the field entirely (not null)
              },
            }
          );
        } catch (unsetError: any) {
          // If removing the field fails due to unique index constraint,
          // set it to a unique temporary value to break the constraint, then remove it
          if (
            unsetError.code === 11000 &&
            unsetError.keyPattern?.stripe_subscription_id
          ) {
            const tempId = `deleted_${existingSubscription._id}_${Date.now()}`;
            await SubscriptionModel.updateOne(
              { _id: existingSubscription._id },
              {
                $set: {
                  stripe_subscription_id: tempId,
                },
              }
            );
            // Now remove it with the temporary value in place
            await SubscriptionModel.updateOne(
              { _id: existingSubscription._id },
              {
                $unset: {
                  stripe_subscription_id: '',
                },
              }
            );
          } else {
            // Re-throw if it's a different error
            throw unsetError;
          }
        }

        // Fetch the updated subscription
        subscription = await SubscriptionModel.findById(existingSubscription._id);
        console.log(
          `✓ Updated existing subscription ${existingSubscription._id} to free tier for user ${userId}`
        );
      } else {
        // Create new free tier subscription only if none exists
        subscription = await SubscriptionModel.create({
          tier: 'free',
          user_id: userId,
          status: 'active',
          current_period_start: new Date(),
          current_period_end: new Date('2099-12-31'), // Free tier never expires
          amount: 0,
          currency: 'usd',
          interval: 'lifetime',
          is_active: true,
          metadata: {
            tier_type: 'free',
            created_via: 'auto_registration',
          },
        });
        console.log(`✓ Created new free subscription for user ${userId}`);
      }

      // CRITICAL: Update user's subscription tier
      await this.syncUserTier(userId, 'free');

      return {
        success: true,
        subscription,
        message: 'Free subscription created successfully',
      };
    } catch (error: any) {
      console.error('Error creating free subscription:', error);
      return {
        success: false,
        subscription: null,
        message: humanizeClientError(
          error,
          'We could not set up your free plan. Please try again.'
        ),
      };
    }
  }

  /**
   * Sync user's subscription tier - ALWAYS call this when subscription changes
   * This ensures User model and Subscription model stay in sync
   */
  public static async syncUserTier(
    userId: string | mongoose.Types.ObjectId,
    tier: SubscriptionTier
  ) {
    try {
      // Validate tier
      if (!isValidTier(tier)) {
        console.error(`Invalid tier: ${tier}, defaulting to free`);
        tier = 'free';
      }

      const result = await UserModel.findByIdAndUpdate(
        userId,
        { subscription_tier: tier },
        { new: true }
      );

      if (!result) {
        throw new Error(`User ${userId} not found`);
      }

      console.log(`✓ User ${userId} tier synced to: ${tier}`);

      return {
        success: true,
        tier,
        message: 'User tier synced successfully',
      };
    } catch (error: any) {
      console.error('✗ Error syncing user tier:', error);
      return {
        success: false,
        tier: 'free',
        message: humanizeClientError(
          error,
          'We could not sync your subscription tier. Please try again.'
        ),
      };
    }
  }

  /**
   * Update user's subscription tier
   * @deprecated Use syncUserTier instead for better clarity
   */
  public static async updateUserSubscriptionTier(
    userId: string | mongoose.Types.ObjectId,
    tier: SubscriptionTier
  ) {
    return this.syncUserTier(userId, tier);
  }

  /**
   * Get user's active subscription with tier information
   * Always returns the tier from User model as source of truth
   */
  public static async getUserActiveSubscription(
    userId: string | mongoose.Types.ObjectId
  ) {
    try {
      type SubscriptionLean = {
        _id: mongoose.Types.ObjectId;
        tier: SubscriptionTier;
      } | null;
      type UserLean = { subscription_tier?: SubscriptionTier } | null;

      const subscription = (await SubscriptionModel.findOne({
        user_id: userId,
        is_active: true,
      })
        .sort({ created_at: -1 })
        .lean()) as SubscriptionLean;

      const user = (await UserModel.findById(userId)
        .select('subscription_tier')
        .lean()) as UserLean;
      const tier = (user?.subscription_tier || 'free') as SubscriptionTier;

      // If there's a mismatch, sync them
      if (subscription && subscription.tier !== tier) {
        console.warn(
          `⚠ Tier mismatch detected for user ${userId}. Subscription: ${subscription.tier}, User: ${tier}`
        );
        console.log('Syncing subscription tier to match user tier...');
        await SubscriptionModel.findByIdAndUpdate(subscription._id, { tier });
      }

      return {
        success: true,
        subscription,
        tier,
      };
    } catch (error: any) {
      console.error('Error getting user subscription:', error);
      return {
        success: false,
        subscription: null,
        tier: 'free' as SubscriptionTier,
      };
    }
  }

  /**
   * Check if user has access to a feature based on their subscription tier
   */
  public static async checkFeatureAccess(
    userId: string | mongoose.Types.ObjectId,
    feature: string
  ): Promise<boolean> {
    try {
      const { tier } = await this.getUserActiveSubscription(userId);

      // Define feature access by tier
      const featureAccess: Record<string, string[]> = {
        free: ['basic_qr', 'limited_scans', 'basic_analytics'],
        personal: [
          'basic_qr',
          'unlimited_scans',
          'advanced_analytics',
          'custom_branding',
          'document_sharing',
        ],
        professional: [
          'basic_qr',
          'unlimited_scans',
          'advanced_analytics',
          'custom_branding',
          'document_sharing',
          'hipaa_compliance',
          'priority_support',
          'api_access',
          'team_management',
        ],
      };

      const tierFeatures = featureAccess[tier] || featureAccess.free;
      return tierFeatures.includes(feature);
    } catch (error) {
      console.error('Error checking feature access:', error);
      return false;
    }
  }

  /**
   * Update or create subscription and sync user tier
   * This is the main method to use when subscription changes
   * ENSURES ONLY ONE SUBSCRIPTION DOCUMENT PER USER
   */
  public static async updateSubscription(
    userId: string | mongoose.Types.ObjectId,
    tier: SubscriptionTier,
    subscriptionData: Partial<any>
  ) {
    try {
      // Validate tier
      if (!isValidTier(tier)) {
        throw new Error(`Invalid tier: ${tier}`);
      }

      // Find the user's existing subscription (there should only be one active)
      const existingSubscription = await SubscriptionModel.findOne({
        user_id: userId,
        is_active: true,
      });

      let subscription;

      if (existingSubscription) {
        // Update the existing subscription document
        subscription = await SubscriptionModel.findByIdAndUpdate(
          existingSubscription._id,
          { ...subscriptionData, tier, user_id: userId, is_active: true },
          { new: true }
        );
        console.log(
          `✓ Updated existing subscription ${existingSubscription._id} for user ${userId}`
        );
      } else {
        // Create new subscription only if none exists
        subscription = await SubscriptionModel.create({
          ...subscriptionData,
          tier,
          user_id: userId,
          is_active: true,
        });
        console.log(
          `✓ Created new subscription ${subscription._id} for user ${userId}`
        );
      }

      // CRITICAL: Sync user tier
      await this.syncUserTier(userId, tier);

      console.log(`✓ Subscription synced for user ${userId}, tier: ${tier}`);

      return {
        success: true,
        subscription,
        tier,
        message: 'Subscription updated successfully',
      };
    } catch (error: any) {
      console.error('✗ Error updating subscription:', error);
      return {
        success: false,
        subscription: null,
        tier: 'free' as SubscriptionTier,
        message: humanizeClientError(
          error,
          'We could not update your subscription. Please try again.'
        ),
      };
    }
  }
}
