import { describe, it, expect, vi, type Mock } from 'vitest';
import { GetUserUseCase } from './GetUserUseCase';
import { User } from '../../domain/entities/User';
import type { IUserRepository, StoredUser } from '../../domain/repositories/IUserRepository';
import type { Logger, UseCaseOutputPort } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';

type GetUserOutput = Result<{ user: User }, unknown>;

describe('GetUserUseCase', () => {
  let userRepository: {
    findById: Mock;
  };
  let logger: Logger;
  let output: UseCaseOutputPort<GetUserOutput> & { present: Mock };
  let useCase: GetUserUseCase;

  beforeEach(() => {
    userRepository = {
      findById: vi.fn(),
    };

    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    } as unknown as Logger;

    output = {
      present: vi.fn(),
    };

    useCase = new GetUserUseCase(
      userRepository as unknown as IUserRepository,
      logger,
      output,
    );
  });

  it('returns a User when the user exists', async () => {
    const storedUser: StoredUser = {
      id: 'user-1',
      email: 'test@example.com',
      displayName: 'Test User',
      passwordHash: 'hash',
      salt: 'salt',
      primaryDriverId: 'driver-1',
      createdAt: new Date(),
    };

    userRepository.findById.mockResolvedValue(storedUser);

    const result = await useCase.execute({ userId: 'user-1' });

    expect(userRepository.findById).toHaveBeenCalledWith('user-1');
    expect(result.isOk()).toBe(true);
    expect(output.present).toHaveBeenCalled();
    const callArgs = output.present.mock.calls?.[0]?.[0];
    expect(callArgs).toBeInstanceOf(Result);
    const user = (callArgs as GetUserOutput).unwrap().user;
    expect(user).toBeInstanceOf(User);
    expect(user.getId().value).toBe('user-1');
    expect(user.getDisplayName()).toBe('Test User');
  });

  it('returns error when the user does not exist', async () => {
    userRepository.findById.mockResolvedValue(null);

    const result = await useCase.execute({ userId: 'missing-user' });

    expect(userRepository.findById).toHaveBeenCalledWith('missing-user');
    expect(result.isErr()).toBe(true);
  });
});