import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { Season } from '../../domain/entities/season/Season';
import type { LeagueRepository } from '../../domain/repositories/LeagueRepository';
import type { SeasonRepository } from '../../domain/repositories/SeasonRepository';

export interface ListSeasonsForLeagueInput {
  leagueId: string;
}

export type ListSeasonsForLeagueErrorCode = 'LEAGUE_NOT_FOUND' | 'REPOSITORY_ERROR';

export interface ListSeasonsForLeagueResult {
  seasons: Season[];
}

export class ListSeasonsForLeagueUseCase {
  constructor(
    private readonly seasonRepository: SeasonRepository,
    private readonly leagueRepository: LeagueRepository,
  ) {}

  async execute(
    input: ListSeasonsForLeagueInput,
  ): Promise<Result<ListSeasonsForLeagueResult, ApplicationErrorCode<ListSeasonsForLeagueErrorCode, { message: string }>>> {
    try {
      const leagueExists = await this.leagueRepository.exists(input.leagueId);

      if (!leagueExists) {
        return Result.err({
          code: 'LEAGUE_NOT_FOUND',
          details: { message: 'League not found' },
        });
      }

      const seasons = await this.seasonRepository.findByLeagueId(input.leagueId);

      return Result.ok({ seasons });
    } catch (error: unknown) {
      const message = error instanceof Error ? error.message : 'Failed to list seasons for league';

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