import type { UseCase } from '@core/shared/application/UseCase';
import type { Logger } from '@core/shared/domain/Logger';
import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { User } from '../../domain/entities/User';
import { AuthRepository } from '../../domain/repositories/AuthRepository';
import { PasswordHashingService } from '../../domain/services/PasswordHashingService';
import { EmailAddress } from '../../domain/value-objects/EmailAddress';

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, LoginResult, LoginErrorCode> {
  constructor(
    private readonly authRepo: AuthRepository,
    private readonly passwordService: PasswordHashingService,
    private readonly logger: Logger,
  ) {}

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