import type { Logger } from '@core/shared/domain/Logger';
import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

import { Race } from '../../domain/entities/Race';
import type { Season } from '../../domain/entities/season/Season';
import { RaceRepository } from '../../domain/repositories/RaceRepository';
import { SeasonRepository } from '../../domain/repositories/SeasonRepository';

export interface CreateLeagueSeasonScheduleRaceInput {
  leagueId: string;
  seasonId: string;
  track: string;
  car: string;
  scheduledAt: Date;
}

export type CreateLeagueSeasonScheduleRaceResult = {
  raceId: string;
};

export type CreateLeagueSeasonScheduleRaceErrorCode =
  | 'SEASON_NOT_FOUND'
  | 'RACE_OUTSIDE_SEASON_WINDOW'
  | 'INVALID_INPUT'
  | 'REPOSITORY_ERROR';

export class CreateLeagueSeasonScheduleRaceUseCase {
  constructor(
    private readonly seasonRepository: SeasonRepository,
    private readonly raceRepository: RaceRepository,
    private readonly logger: Logger,
    private readonly deps: { generateRaceId: () => string },
  ) {}

  async execute(
    input: CreateLeagueSeasonScheduleRaceInput,
  ): Promise<
    Result<
      CreateLeagueSeasonScheduleRaceResult,
      ApplicationErrorCode<CreateLeagueSeasonScheduleRaceErrorCode, { message: string }>
    >
  > {
    this.logger.debug('Creating league season schedule race', {
      leagueId: input.leagueId,
      seasonId: input.seasonId,
    });

    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' },
        });
      }

      if (!this.isWithinSeasonWindow(season, input.scheduledAt)) {
        return Result.err({
          code: 'RACE_OUTSIDE_SEASON_WINDOW',
          details: { message: 'Race scheduledAt is outside the season schedule window' },
        });
      }

      const id = this.deps.generateRaceId();

      let race: Race;
      try {
        race = Race.create({
          id,
          leagueId: input.leagueId,
          track: input.track,
          car: input.car,
          scheduledAt: input.scheduledAt,
        });
      } catch (err) {
        const message = err instanceof Error ? err.message : 'Invalid race input';
        return Result.err({ code: 'INVALID_INPUT', details: { message } });
      }

      await this.raceRepository.create(race);

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

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

  private isWithinSeasonWindow(season: Season, scheduledAt: Date): boolean {
    if (!season.startDate || !season.endDate) {
      return true;
    }
    return scheduledAt >= season.startDate && scheduledAt <= season.endDate;
  }
}