/**
 * Application Use Case: AwardPrizeUseCase
 *
 * Awards a prize to a driver.
 */

import type { IPrizeRepository } from '../../domain/repositories/IPrizeRepository';
import type {
  IAwardPrizePresenter,
  AwardPrizeResultDTO,
  AwardPrizeViewModel,
} from '../presenters/IAwardPrizePresenter';
import type { UseCase } from '@core/shared/application/UseCase';

export interface AwardPrizeInput {
  prizeId: string;
  driverId: string;
}

export class AwardPrizeUseCase
  implements UseCase<AwardPrizeInput, AwardPrizeResultDTO, AwardPrizeViewModel, IAwardPrizePresenter>
{
  constructor(private readonly prizeRepository: IPrizeRepository) {}

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

    const { prizeId, driverId } = input;

    const prize = await this.prizeRepository.findById(prizeId);
    if (!prize) {
      throw new Error('Prize not found');
    }

    if (prize.awarded) {
      throw new Error('Prize has already been awarded');
    }

    prize.awarded = true;
    prize.awardedTo = driverId;
    prize.awardedAt = new Date();

    const updatedPrize = await this.prizeRepository.update(prize);

    const dto: AwardPrizeResultDTO = {
      prize: {
        id: updatedPrize.id,
        leagueId: updatedPrize.leagueId,
        seasonId: updatedPrize.seasonId,
        position: updatedPrize.position,
        name: updatedPrize.name,
        amount: updatedPrize.amount,
        type: updatedPrize.type,
        description: updatedPrize.description,
        awarded: updatedPrize.awarded,
        awardedTo: updatedPrize.awardedTo,
        awardedAt: updatedPrize.awardedAt,
        createdAt: updatedPrize.createdAt,
      },
    };

    presenter.present(dto);
  }
}