import { describe, it, expect, vi, type Mock } from 'vitest';
import {
  LoginWithEmailUseCase,
  type LoginWithEmailInput,
  type LoginWithEmailResult,
  type LoginWithEmailErrorCode,
} from './LoginWithEmailUseCase';
import type { IUserRepository, StoredUser } from '../../domain/repositories/IUserRepository';
import type { IdentitySessionPort } from '../ports/IdentitySessionPort';
import type { UseCaseOutputPort, Logger } from '@core/shared/application';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { Result } from '@core/shared/application/Result';

describe('LoginWithEmailUseCase', () => {
  let userRepository: {
    findByEmail: Mock;
  };
  let sessionPort: {
    createSession: Mock;
    getCurrentSession: Mock;
    clearSession: Mock;
  };
  let logger: Logger & { error: Mock };
  let output: UseCaseOutputPort<LoginWithEmailResult> & { present: Mock };
  let useCase: LoginWithEmailUseCase;

  beforeEach(() => {
    userRepository = {
      findByEmail: vi.fn(),
    };
    sessionPort = {
      createSession: vi.fn(),
      getCurrentSession: vi.fn(),
      clearSession: vi.fn(),
    };
    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    } as unknown as Logger & { error: Mock };
    output = {
      present: vi.fn(),
    } as unknown as UseCaseOutputPort<LoginWithEmailResult> & { present: Mock };

    useCase = new LoginWithEmailUseCase(
      userRepository as unknown as IUserRepository,
      sessionPort as unknown as IdentitySessionPort,
      logger,
      output,
    );
  });

  it('returns ok and presents session result for valid credentials', async () => {
    const input: LoginWithEmailInput = {
      email: 'Test@Example.com',
      password: 'password123',
    };

    const storedUser: StoredUser = {
      id: 'user-1',
      email: 'test@example.com',
      displayName: 'Test User',
      passwordHash: '',
      salt: 'salt',
      createdAt: new Date(),
    };

    storedUser.passwordHash = await (useCase as unknown as { hashPassword: (p: string, s: string) => Promise<string> }).hashPassword(
      input.password,
      storedUser.salt,
    );

    const session = {
      user: {
        id: storedUser.id,
        email: storedUser.email,
        displayName: storedUser.displayName,
      },
      issuedAt: Date.now(),
      expiresAt: Date.now() + 1000,
      token: 'token-123',
    };

    userRepository.findByEmail.mockResolvedValue(storedUser);
    sessionPort.createSession.mockResolvedValue(session);

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

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

    expect(userRepository.findByEmail).toHaveBeenCalledWith('test@example.com');
    expect(sessionPort.createSession).toHaveBeenCalledWith({
      id: storedUser.id,
      displayName: storedUser.displayName,
      email: storedUser.email,
    });

    expect(output.present).toHaveBeenCalledTimes(1);
    const presented = output.present.mock.calls[0]![0] as LoginWithEmailResult;
    expect(presented.sessionToken).toBe('token-123');
    expect(presented.userId).toBe(storedUser.id);
    expect(presented.displayName).toBe(storedUser.displayName);
    expect(presented.email).toBe(storedUser.email);
  });

  it('returns INVALID_INPUT when email or password is missing', async () => {
    const result1 = await useCase.execute({ email: '', password: 'x' });
    const result2 = await useCase.execute({ email: 'a@example.com', password: '' });

    expect(result1.isErr()).toBe(true);
    expect(result1.unwrapErr().code).toBe('INVALID_INPUT');
    expect(result2.isErr()).toBe(true);
    expect(result2.unwrapErr().code).toBe('INVALID_INPUT');
    expect(output.present).not.toHaveBeenCalled();
  });

  it('returns INVALID_CREDENTIALS when user does not exist', async () => {
    const input: LoginWithEmailInput = {
      email: 'missing@example.com',
      password: 'password',
    };

    userRepository.findByEmail.mockResolvedValue(null);

    const result: Result<void, ApplicationErrorCode<LoginWithEmailErrorCode, { 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 email or password');
    expect(output.present).not.toHaveBeenCalled();
  });

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

    const storedUser: StoredUser = {
      id: 'user-1',
      email: 'test@example.com',
      displayName: 'Test User',
      passwordHash: 'different-hash',
      salt: 'salt',
      createdAt: new Date(),
    };

    userRepository.findByEmail.mockResolvedValue(storedUser);

    const result: Result<void, ApplicationErrorCode<LoginWithEmailErrorCode, { 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 email or password');
    expect(output.present).not.toHaveBeenCalled();
  });

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

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

    const result: Result<void, ApplicationErrorCode<LoginWithEmailErrorCode, { 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();
  });
});
