/**
 * Application Use Case: GetPrizesUseCase
 *
 * Retrieves prizes for a league or season.
 */

import type { IPrizeRepository } from '../../domain/repositories/IPrizeRepository';
import type {
  IGetPrizesPresenter,
  GetPrizesResultDTO,
  GetPrizesViewModel,
} from '../presenters/IGetPrizesPresenter';
import type { UseCase } from '@core/shared/application/UseCase';

export interface GetPrizesInput {
  leagueId: string;
  seasonId?: string;
}

export class GetPrizesUseCase
  implements UseCase<GetPrizesInput, GetPrizesResultDTO, GetPrizesViewModel, IGetPrizesPresenter>
{
  constructor(private readonly prizeRepository: IPrizeRepository) {}

  async execute(
    input: GetPrizesInput,
    presenter: IGetPrizesPresenter,
  ): Promise<void> {
    presenter.reset();

    const { leagueId, seasonId } = input;

    let prizes;
    if (seasonId) {
      prizes = await this.prizeRepository.findByLeagueIdAndSeasonId(leagueId, seasonId);
    } else {
      prizes = await this.prizeRepository.findByLeagueId(leagueId);
    }

    prizes.sort((a, b) => a.position - b.position);

    const dto: GetPrizesResultDTO = {
      prizes: prizes.map(prize => ({
        id: prize.id,
        leagueId: prize.leagueId,
        seasonId: prize.seasonId,
        position: prize.position,
        name: prize.name,
        amount: prize.amount,
        type: prize.type,
        description: prize.description,
        awarded: prize.awarded,
        awardedTo: prize.awardedTo,
        awardedAt: prize.awardedAt,
        createdAt: prize.createdAt,
      })),
    };

    presenter.present(dto);
  }
}