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

export interface GetLeagueSeasonsUseCaseParams {
  leagueId: string;
}

export class GetLeagueSeasonsUseCase {
  constructor(private readonly seasonRepository: ISeasonRepository) {}

  async execute(params: GetLeagueSeasonsUseCaseParams): Promise<Result<GetLeagueSeasonsViewModel, ApplicationErrorCode<'REPOSITORY_ERROR', { message: string }>>> {
    try {
      const seasons = await this.seasonRepository.findByLeagueId(params.leagueId);
      const activeCount = seasons.filter(s => s.status === 'active').length;
      const viewModel: GetLeagueSeasonsViewModel = {
        seasons: seasons.map(s => ({
          seasonId: s.id,
          name: s.name,
          status: s.status,
          startDate: s.startDate ?? new Date(),
          endDate: s.endDate ?? new Date(),
          isPrimary: false,
          isParallelActive: s.status === 'active' && activeCount > 1
        }))
      };
      return Result.ok(viewModel);
    } catch {
      return Result.err({ code: 'REPOSITORY_ERROR', details: { message: 'Failed to fetch seasons' } });
    }
  }
}