import { describe, it, expect, vi, type Mock } from 'vitest';
import { CreateAchievementUseCase, type IAchievementRepository } from './CreateAchievementUseCase';
import { Achievement } from '@core/identity/domain/entities/Achievement';
import type { Logger, UseCaseOutputPort } from '@core/shared/application';

type CreateAchievementOutput = {
  achievement: Achievement;
};

describe('CreateAchievementUseCase', () => {
  let achievementRepository: {
    save: Mock;
    findById: Mock;
  };
  let logger: Logger;
  let output: UseCaseOutputPort<CreateAchievementOutput> & { present: Mock };
  let useCase: CreateAchievementUseCase;

  beforeEach(() => {
    achievementRepository = {
      save: vi.fn(),
      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 CreateAchievementUseCase(
      achievementRepository as unknown as IAchievementRepository,
      logger,
      output,
    );
  });

  it('creates an achievement and persists it', async () => {
    const props = {
      id: 'achv-1',
      name: 'First Win',
      description: 'Awarded for winning your first race',
      category: 'driver' as const,
      rarity: 'common' as const,
      iconUrl: 'https://example.com/icon.png',
      points: 50,
      requirements: [
        {
          type: 'wins' as const,
          value: 1,
          operator: '>=' as const,
        },
      ],
      isSecret: false,
    };

    achievementRepository.save.mockResolvedValue(undefined);

    const result = await useCase.execute(props);

    expect(result.isOk()).toBe(true);
    expect(achievementRepository.save).toHaveBeenCalledTimes(1);
    const savedAchievement = achievementRepository.save.mock.calls?.[0]?.[0];
    expect(savedAchievement).toBeInstanceOf(Achievement);
    expect(savedAchievement.id).toBe(props.id);
    expect(savedAchievement.name).toBe(props.name);
    expect(output.present).toHaveBeenCalledWith({ achievement: savedAchievement });
  });
});