import { EmailAddress } from '../../domain/value-objects/EmailAddress';
import { User } from '../../domain/entities/User';
import { IAuthRepository } from '../../domain/repositories/IAuthRepository';
import { IPasswordHashingService } from '../../domain/services/PasswordHashingService';

/**
 * Application Use Case: LoginUseCase
 *
 * Handles user login by verifying credentials.
 */
export class LoginUseCase {
  constructor(
    private authRepo: IAuthRepository,
    private passwordService: IPasswordHashingService
  ) {}

  async execute(email: string, password: string): Promise<User> {
    const emailVO = EmailAddress.create(email);
    const user = await this.authRepo.findByEmail(emailVO);
    if (!user || !user.getPasswordHash()) {
      throw new Error('Invalid credentials');
    }
    const isValid = await this.passwordService.verify(password, user.getPasswordHash()!.value);
    if (!isValid) {
      throw new Error('Invalid credentials');
    }
    return user;
  }
}