/**
 * Application Use Case: DeletePrizeUseCase
 *
 * Deletes a prize.
 */

import type { IPrizeRepository } from '../../domain/repositories/IPrizeRepository';
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 DeletePrizeInput {
  prizeId: string;
}

export interface DeletePrizeResult {
  success: boolean;
}

export type DeletePrizeErrorCode = 'PRIZE_NOT_FOUND' | 'CANNOT_DELETE_AWARDED_PRIZE';

export class DeletePrizeUseCase
  implements UseCase<DeletePrizeInput, void, DeletePrizeErrorCode>
{
  constructor(
    private readonly prizeRepository: IPrizeRepository,
    private readonly output: UseCaseOutputPort<DeletePrizeResult>,
  ) {}

  async execute(input: DeletePrizeInput): Promise<Result<void, ApplicationErrorCode<DeletePrizeErrorCode>>> {
    const { prizeId } = 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: 'CANNOT_DELETE_AWARDED_PRIZE' as const });
    }

    await this.prizeRepository.delete(prizeId);

    this.output.present({ success: true });

    return Result.ok(undefined);
  }
}