import type { Logger, UseCaseOutputPort } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

import type { IRaceRepository } from '../../domain/repositories/IRaceRepository';
import type { ISeasonRepository } from '../../domain/repositories/ISeasonRepository';

export type DeleteLeagueSeasonScheduleRaceInput = {
  leagueId: string;
  seasonId: string;
  raceId: string;
};

export type DeleteLeagueSeasonScheduleRaceResult = {
  success: true;
};

export type DeleteLeagueSeasonScheduleRaceErrorCode =
  | 'SEASON_NOT_FOUND'
  | 'RACE_NOT_FOUND'
  | 'REPOSITORY_ERROR';

export class DeleteLeagueSeasonScheduleRaceUseCase {
  constructor(
    private readonly seasonRepository: ISeasonRepository,
    private readonly raceRepository: IRaceRepository,
    private readonly logger: Logger,
    private readonly output: UseCaseOutputPort<DeleteLeagueSeasonScheduleRaceResult>,
  ) {}

  async execute(
    input: DeleteLeagueSeasonScheduleRaceInput,
  ): Promise<
    Result<
      void,
      ApplicationErrorCode<DeleteLeagueSeasonScheduleRaceErrorCode, { message: string }>
    >
  > {
    this.logger.debug('Deleting league season schedule race', {
      leagueId: input.leagueId,
      seasonId: input.seasonId,
      raceId: input.raceId,
    });

    try {
      const season = await this.seasonRepository.findById(input.seasonId);
      if (!season || season.leagueId !== input.leagueId) {
        return Result.err({
          code: 'SEASON_NOT_FOUND',
          details: { message: 'Season not found for league' },
        });
      }

      const existing = await this.raceRepository.findById(input.raceId);
      if (!existing || existing.leagueId !== input.leagueId) {
        return Result.err({
          code: 'RACE_NOT_FOUND',
          details: { message: 'Race not found for league' },
        });
      }

      await this.raceRepository.delete(input.raceId);

      const result: DeleteLeagueSeasonScheduleRaceResult = { success: true };
      this.output.present(result);

      return Result.ok(undefined);
    } catch (err) {
      const error = err instanceof Error ? err : new Error('Unknown error');
      this.logger.error('Failed to delete league season schedule race', error, {
        leagueId: input.leagueId,
        seasonId: input.seasonId,
        raceId: input.raceId,
      });

      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message: error.message },
      });
    }
  }
}