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

export type ListSeasonsForLeagueInput = {
  leagueId: string;
};

export type LeagueSeasonSummary = {
  id: string;
  name: string;
  status: SeasonStatus;
  startsAt: Date | undefined;
  endsAt: Date | undefined;
};

export type ListSeasonsForLeagueResult = {
  leagueId: string;
  seasons: LeagueSeasonSummary[];
};

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

/**
 * ListSeasonsForLeagueUseCase
 */
export class ListSeasonsForLeagueUseCase {
  constructor(
    private readonly leagueRepository: ILeagueRepository,
    private readonly seasonRepository: ISeasonRepository,
    private readonly output: UseCaseOutputPort<ListSeasonsForLeagueResult>,
  ) {}

  async execute(
    query: ListSeasonsForLeagueInput,
  ): Promise<
    Result<void, ApplicationErrorCode<ListSeasonsForLeagueErrorCode, { message: string }>>
  > {
    try {
      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(query.leagueId);

      const result: ListSeasonsForLeagueResult = {
        leagueId: query.leagueId,
        seasons: seasons.map((season) => ({
          id: season.id,
          name: season.name,
          status: season.status,
          startsAt: season.startDate,
          endsAt: season.endDate,
        })),
      };

      this.output.present(result);

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

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