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

export type GetLeagueAdminInput = {
  leagueId: string;
};

export type GetLeagueAdminResult = {
  league: League;
};

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

export class GetLeagueAdminUseCase {
  constructor(
    private readonly leagueRepository: ILeagueRepository,
    private readonly output: UseCaseOutputPort<GetLeagueAdminResult>,
  ) {}

  async execute(
    input: GetLeagueAdminInput,
  ): Promise<Result<void, ApplicationErrorCode<GetLeagueAdminErrorCode, { message: string }>>> {
    try {
      const league = await this.leagueRepository.findById(input.leagueId);
      if (!league) {
        return Result.err({ code: 'LEAGUE_NOT_FOUND', details: { message: 'League not found' } });
      }

      this.output.present({ league });

      return Result.ok(undefined);
    } catch (error) {
      const err = error instanceof Error ? error : new Error('Unknown error');
      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message: err.message ?? 'Failed to load league admin data' },
      });
    }
  }
}