import type { Logger } from '@core/shared/domain/Logger';
import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { describe, expect, it, vi, type Mock } from 'vitest';
import { Avatar } from '../../domain/entities/Avatar';
import {
    GetAvatarUseCase,
    type GetAvatarErrorCode,
    type GetAvatarInput,
} from './GetAvatarUseCase';

describe('GetAvatarUseCase', () => {
  let avatarRepo: {
    findActiveByDriverId: Mock;
    save: Mock;
  };
  let logger: Logger;
  let useCase: GetAvatarUseCase;

  beforeEach(() => {
    avatarRepo = {
      findActiveByDriverId: vi.fn(),
      save: vi.fn(),
    };

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

    useCase = new GetAvatarUseCase(
      avatarRepo as unknown as AvatarRepository,
      logger,
    );
  });

  it('returns AVATAR_NOT_FOUND when no avatar exists for driver', async () => {
    avatarRepo.findActiveByDriverId.mockResolvedValue(null);

    const input: GetAvatarInput = { driverId: 'driver-1' };
    const result = await useCase.execute(input);

    expect(avatarRepo.findActiveByDriverId).toHaveBeenCalledWith('driver-1');
    expect(result).toBeInstanceOf(Result);
    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<
      GetAvatarErrorCode,
      { message: string }
    >;
    expect(err.code).toBe('AVATAR_NOT_FOUND');
  });

  it('returns GetAvatarResult when avatar exists', async () => {
    const avatar = Avatar.create({
      id: 'avatar-1',
      driverId: 'driver-1',
      mediaUrl: 'https://example.com/avatar.png',
    });

    avatarRepo.findActiveByDriverId.mockResolvedValue(avatar);

    const input: GetAvatarInput = { driverId: 'driver-1' };
    const result = await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    expect(avatarRepo.findActiveByDriverId).toHaveBeenCalledWith('driver-1');

    const successResult = result.unwrap();
    expect(successResult).toEqual({
      avatar: {
        id: avatar.id,
        driverId: avatar.driverId,
        mediaUrl: avatar.mediaUrl.value,
        selectedAt: avatar.selectedAt,
      },
    });
  });

  it('handles repository errors by returning REPOSITORY_ERROR', async () => {
    avatarRepo.findActiveByDriverId.mockRejectedValue(new Error('DB error'));

    const input: GetAvatarInput = { driverId: 'driver-1' };
    const result = await useCase.execute(input);

    expect((logger.error as unknown as Mock)).toHaveBeenCalled();
    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<
      GetAvatarErrorCode,
      { message: string }
    >;
    expect(err.code).toBe('REPOSITORY_ERROR');
  });
});