import { describe, it, expect, vi, type Mock } from 'vitest';
import { CreatePrizeUseCase, type CreatePrizeInput } from './CreatePrizeUseCase';
import type { IPrizeRepository } from '../../domain/repositories/IPrizeRepository';
import { PrizeType, type Prize } from '../../domain/entities/Prize';
import type { UseCaseOutputPort } from '@core/shared/application/UseCaseOutputPort';

describe('CreatePrizeUseCase', () => {
  let prizeRepository: { findByPosition: Mock; create: Mock };
  let output: { present: Mock };
  let useCase: CreatePrizeUseCase;

  beforeEach(() => {
    prizeRepository = {
      findByPosition: vi.fn(),
      create: vi.fn(),
    };

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

    useCase = new CreatePrizeUseCase(
      prizeRepository as unknown as IPrizeRepository,
      output as unknown as UseCaseOutputPort<unknown>,
    );
  });

  it('returns PRIZE_ALREADY_EXISTS when prize already exists for position', async () => {
    const existingPrize: Prize = {
      id: 'prize-existing',
      leagueId: 'league-1',
      seasonId: 'season-1',
      position: 1,
      name: 'Winner',
      amount: 100,
      type: PrizeType.CASH,
      awarded: false,
      createdAt: new Date(),
    };

    prizeRepository.findByPosition.mockResolvedValue(existingPrize);

    const input: CreatePrizeInput = {
      leagueId: 'league-1',
      seasonId: 'season-1',
      position: 1,
      name: 'Winner',
      amount: 100,
      type: PrizeType.CASH,
    };

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr().code).toBe('PRIZE_ALREADY_EXISTS');
    expect(prizeRepository.create).not.toHaveBeenCalled();
    expect(output.present).not.toHaveBeenCalled();
  });

  it('creates prize and presents created prize', async () => {
    prizeRepository.findByPosition.mockResolvedValue(null);
    prizeRepository.create.mockImplementation(async (p: Prize) => p);

    const input: CreatePrizeInput = {
      leagueId: 'league-1',
      seasonId: 'season-1',
      position: 1,
      name: 'Winner',
      amount: 100,
      type: PrizeType.CASH,
      description: 'Top prize',
    };

    const result = await useCase.execute(input);

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

    expect(prizeRepository.findByPosition).toHaveBeenCalledWith('league-1', 'season-1', 1);

    expect(prizeRepository.create).toHaveBeenCalledWith({
      id: expect.stringContaining('prize-'),
      leagueId: 'league-1',
      seasonId: 'season-1',
      position: 1,
      name: 'Winner',
      amount: 100,
      type: PrizeType.CASH,
      awarded: false,
      createdAt: expect.any(Date),
      description: 'Top prize',
    });

    expect(output.present).toHaveBeenCalledWith({
      prize: expect.objectContaining({
        leagueId: 'league-1',
        seasonId: 'season-1',
        position: 1,
        awarded: false,
      }),
    });
  });
});