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

import type { IPrizeRepository } from '../../domain/repositories/IPrizeRepository';
import type { Prize } from '../../domain/entities/Prize';
import type { UseCase } from '@core/shared/application/UseCase';
import type { UseCaseOutputPort } from '@core/shared/application/UseCaseOutputPort';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

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

export interface AwardPrizeResult {
  prize: Prize;
}

export type AwardPrizeErrorCode = 'PRIZE_NOT_FOUND' | 'PRIZE_ALREADY_AWARDED';

export class AwardPrizeUseCase
  implements UseCase<AwardPrizeInput, void, AwardPrizeErrorCode>
{
  constructor(
    private readonly prizeRepository: IPrizeRepository,
    private readonly output: UseCaseOutputPort<AwardPrizeResult>,
  ) {}

  async execute(input: AwardPrizeInput): Promise<Result<void, ApplicationErrorCode<AwardPrizeErrorCode>>> {
    const { prizeId, driverId } = input;

    const prize = await this.prizeRepository.findById(prizeId);
    if (!prize) {
      return Result.err({ code: 'PRIZE_NOT_FOUND' as const });
    }

    if (prize.awarded) {
      return Result.err({ code: 'PRIZE_ALREADY_AWARDED' as const });
    }

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

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

    this.output.present({ prize: updatedPrize });

    return Result.ok(undefined);
  }
}