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 { UseCaseOutputPort, 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<LoginErrorCode, { message: string }>;

/**
 * Application Use Case: LoginUseCase
 *
 * Handles user login by verifying credentials.
 */
export class LoginUseCase implements UseCase<LoginInput, void, LoginErrorCode> {
  constructor(
    private readonly authRepo: IAuthRepository,
    private readonly passwordService: IPasswordHashingService,
    private readonly logger: Logger,
    private readonly output: UseCaseOutputPort<LoginResult>,
  ) {}

  async execute(input: LoginInput): Promise<Result<void, LoginApplicationError>> {
    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<void, LoginApplicationError>({
          code: 'INVALID_CREDENTIALS',
          details: { message: 'Invalid credentials' },
        });
      }

      this.output.present({ user });
      return Result.ok(undefined);
    } 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<void, LoginApplicationError>({
        code: 'REPOSITORY_ERROR',
        details: { message },
      });
    }
  }
}