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'; import { Result } from '@core/shared/application/Result'; import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode'; import type { Logger, UseCase } from '@core/shared/application'; export type LoginInput = { email: string; password: string; }; export type LoginResult = { user: User; }; export type LoginErrorCode = 'INVALID_CREDENTIALS' | 'REPOSITORY_ERROR'; export type LoginApplicationError = ApplicationErrorCode; /** * Application Use Case: LoginUseCase * * Handles user login by verifying credentials. */ export class LoginUseCase implements UseCase { constructor( private readonly authRepo: IAuthRepository, private readonly passwordService: IPasswordHashingService, private readonly logger: Logger, ) {} async execute(input: LoginInput): Promise> { try { const emailVO = EmailAddress.create(input.email); const user = await this.authRepo.findByEmail(emailVO); if (!user || !user.getPasswordHash()) { return Result.err({ code: 'INVALID_CREDENTIALS', details: { message: 'Invalid credentials' }, }); } const passwordHash = user.getPasswordHash()!; const isValid = await this.passwordService.verify(input.password, passwordHash.value); if (!isValid) { return Result.err({ code: 'INVALID_CREDENTIALS', details: { message: 'Invalid credentials' }, }); } return Result.ok({ user }); } catch (error) { const message = error instanceof Error && error.message ? error.message : 'Failed to execute LoginUseCase'; this.logger.error('LoginUseCase.execute failed', error instanceof Error ? error : undefined, { input, }); return Result.err({ code: 'REPOSITORY_ERROR', details: { message }, }); } } }