import bcrypt from 'bcryptjs';

export class LoginUserCommandHandler {
  constructor(userRepository, jwtService) {
    this.userRepository = userRepository;
    this.jwtService = jwtService;
  }

  async handle(command) {
    // Find user by email
    const user = await this.userRepository.findByEmail(command.email);
    if (!user) {
      throw new Error('Invalid credentials');
    }

    // Verify password
    const isValidPassword = await bcrypt.compare(command.password, user.password);
    if (!isValidPassword) {
      throw new Error('Invalid credentials');
    }

    // Generate token
    const token = this.jwtService.generateToken({
      id: user.id,
      email: user.email,
      name: user.name
    });

    return { user, token };
  }
}
