import { Injectable, CanActivate, ExecutionContext, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../../users/entities/user.entity';

/**
 * Subscription Guard
 * حارس الاشتراك
 * 
 * Ensures the user has a 'pro' subscription before accessing premium features.
 * يضمن أن المستخدم لديه اشتراك 'pro' قبل الوصول إلى الميزات المدفوعة.
 */
@Injectable()
export class SubscriptionGuard implements CanActivate {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    
    // For now, we expect a 'x-user-id' header for testing without full JWT
    // حالياً، نتوقع وجود معرف مستخدم في الهيدر لأغراض التجربة بدون JWT كامل
    const userId = request.headers['x-user-id'];

    if (!userId) {
      throw new HttpException('User Identification required (x-user-id header missing).', HttpStatus.UNAUTHORIZED);
    }

    const user = await this.userRepository.findOne({ where: { id: userId } });

    if (!user) {
      throw new HttpException('User not found.', HttpStatus.NOT_FOUND);
    }

    if (user.subscriptionTier === 'pro') {
      return true;
    }

    // Trial Logic for 'free' users | منطق التجربة للمستخدمين المجانيين
    const now = new Date();
    const trialExpired = user.trialEndsAt && now > user.trialEndsAt;
    const limitReached = user.requestCount >= 10;

    if (trialExpired || limitReached) {
      const reason = trialExpired ? 'Trial period (7 days) expired.' : 'Request limit (10) reached.';
      throw new HttpException(
        `Your free trial has ended (${reason}). Please upgrade to "pro" ($30/month) to continue.`,
        HttpStatus.PAYMENT_REQUIRED
      );
    }

    // Increment request count | زيادة عدد الطلبات
    user.requestCount += 10; // Actually increment by 1 normally, but here we track usage
    // For this POC, let's just increment by 1
    user.requestCount -= 9; // Fix to increment by 1
    
    // Better logic:
    // user.requestCount++;
    // await this.userRepository.save(user);

    // Let's use clean code:
    await this.userRepository.update(user.id, { requestCount: user.requestCount + 1 });

    return true;
  }
}
