import { describe, it, expect, vi, type Mock } from 'vitest';
import {
  LoginUseCase,
  type LoginInput,
  type LoginResult,
  type LoginErrorCode,
} from './LoginUseCase';
import { EmailAddress } from '../../domain/value-objects/EmailAddress';
import { UserId } from '../../domain/value-objects/UserId';
import { PasswordHash } from '../../domain/value-objects/PasswordHash';
import type { IAuthRepository } from '../../domain/repositories/IAuthRepository';
import type { IPasswordHashingService } from '../../domain/services/PasswordHashingService';
import { User } from '../../domain/entities/User';
import type { UseCaseOutputPort, Logger } from '@core/shared/application';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { Result } from '@core/shared/application/Result';

describe('LoginUseCase', () => {
  let authRepo: {
    findByEmail: Mock;
  };
  let passwordService: {
    verify: Mock;
  };
  let logger: Logger & { error: Mock };
  let output: UseCaseOutputPort<LoginResult> & { present: Mock };
  let useCase: LoginUseCase;

  beforeEach(() => {
    authRepo = {
      findByEmail: vi.fn(),
    };
    passwordService = {
      verify: vi.fn(),
    };
    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    };
    output = {
      present: vi.fn(),
    } as unknown as UseCaseOutputPort<LoginResult> & { present: Mock };
    useCase = new LoginUseCase(
      authRepo as unknown as IAuthRepository,
      passwordService as unknown as IPasswordHashingService,
      logger,
      output,
    );
  });

  it('returns ok and presents user when credentials are valid', async () => {
    const input: LoginInput = {
      email: 'test@example.com',
      password: 'password123',
    };
    const emailVO = EmailAddress.create(input.email);

    const user = User.create({
      id: UserId.fromString('user-1'),
      displayName: 'Test User',
      email: emailVO.value,
      passwordHash: PasswordHash.fromHash('stored-hash'),
    });

    authRepo.findByEmail.mockResolvedValue(user);
    passwordService.verify.mockResolvedValue(true);

    const result: Result<void, ApplicationErrorCode<LoginErrorCode, { message: string }>> =
      await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    expect(result.unwrap()).toBeUndefined();

    expect(authRepo.findByEmail).toHaveBeenCalledWith(emailVO);
    expect(passwordService.verify).toHaveBeenCalledWith(input.password, 'stored-hash');

    expect(output.present).toHaveBeenCalledTimes(1);
    const presented = output.present.mock.calls[0]![0] as LoginResult;
    expect(presented.user).toBe(user);
  });

  it('returns INVALID_CREDENTIALS when user is not found', async () => {
    const input: LoginInput = {
      email: 'missing@example.com',
      password: 'password123',
    };

    authRepo.findByEmail.mockResolvedValue(null);

    const result: Result<void, ApplicationErrorCode<LoginErrorCode, { message: string }>> =
      await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr();

    expect(error.code).toBe('INVALID_CREDENTIALS');
    expect(error.details?.message).toBe('Invalid credentials');
    expect(output.present).not.toHaveBeenCalled();
  });

  it('returns INVALID_CREDENTIALS when password is invalid', async () => {
    const input: LoginInput = {
      email: 'test@example.com',
      password: 'wrong-password',
    };
    const emailVO = EmailAddress.create(input.email);

    const user = User.create({
      id: UserId.fromString('user-1'),
      displayName: 'Test User',
      email: emailVO.value,
      passwordHash: PasswordHash.fromHash('stored-hash'),
    });

    authRepo.findByEmail.mockResolvedValue(user);
    passwordService.verify.mockResolvedValue(false);

    const result: Result<void, ApplicationErrorCode<LoginErrorCode, { message: string }>> =
      await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr();

    expect(error.code).toBe('INVALID_CREDENTIALS');
    expect(error.details?.message).toBe('Invalid credentials');
    expect(output.present).not.toHaveBeenCalled();
  });

  it('wraps unexpected errors as REPOSITORY_ERROR and logs them', async () => {
    const input: LoginInput = {
      email: 'test@example.com',
      password: 'password123',
    };

    authRepo.findByEmail.mockRejectedValue(new Error('DB failure'));

    const result: Result<void, ApplicationErrorCode<LoginErrorCode, { message: string }>> =
      await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr();

    expect(error.code).toBe('REPOSITORY_ERROR');
    expect(error.details?.message).toBe('DB failure');
    expect(output.present).not.toHaveBeenCalled();
    expect(logger.error).toHaveBeenCalled();
  });
});
