import type { ISeasonRepository } from '../../domain/repositories/ISeasonRepository';
import type { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

export interface SeasonSummaryDTO {
  seasonId: string;
  leagueId: string;
  name: string;
  status: import('../../domain/entities/Season').SeasonStatus;
  startDate?: Date;
  endDate?: Date;
  isPrimary: boolean;
}

export interface ListSeasonsForLeagueQuery {
  leagueId: string;
}

export interface ListSeasonsForLeagueResultDTO {
  items: SeasonSummaryDTO[];
}

type ListSeasonsForLeagueErrorCode = 'LEAGUE_NOT_FOUND';

/**
 * ListSeasonsForLeagueUseCase
 */
export class ListSeasonsForLeagueUseCase {
  constructor(
    private readonly leagueRepository: ILeagueRepository,
    private readonly seasonRepository: ISeasonRepository,
  ) {}

  async execute(
    query: ListSeasonsForLeagueQuery,
  ): Promise<Result<ListSeasonsForLeagueResultDTO, ApplicationErrorCode<ListSeasonsForLeagueErrorCode>>> {
    const league = await this.leagueRepository.findById(query.leagueId);
    if (!league) {
      return Result.err({
        code: 'LEAGUE_NOT_FOUND',
        details: { message: `League not found: ${query.leagueId}` },
      });
    }

    const seasons = await this.seasonRepository.listByLeague(league.id);
    const items: SeasonSummaryDTO[] = seasons.map((s) => ({
      seasonId: s.id,
      leagueId: s.leagueId,
      name: s.name,
      status: s.status,
      ...(s.startDate !== undefined ? { startDate: s.startDate } : {}),
      ...(s.endDate !== undefined ? { endDate: s.endDate } : {}),
      // League currently does not track primarySeasonId, so mark false for now.
      isPrimary: false,
    }));

    return Result.ok({ items });
  }
}