import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../entities/user.entity';

@Injectable()
export class UsersService {
  private readonly logger = new Logger(UsersService.name);

  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  async findAll(): Promise<User[]> {
    return this.userRepository.find();
  }

  async findById(id: string): Promise<User> {
    const user = await this.userRepository.findOne({ where: { id } });
    if (!user) {
      throw new NotFoundException(`User with ID ${id} not found`);
    }
    return user;
  }

  async findByEmail(email: string): Promise<User | null> {
    return this.userRepository.findOne({ where: { email } });
  }

  async updateSubscription(userId: string, tier: 'free' | 'pro', durationDays: number): Promise<User> {
    const user = await this.findById(userId);
    user.subscriptionTier = tier;
    
    const expiry = new Date();
    expiry.setDate(expiry.getDate() + durationDays);
    user.subscriptionExpiresAt = expiry;
    user.lastPaymentDate = new Date();

    return this.userRepository.save(user);
  }
}
