import { LeagueRepository, LeagueData } from '../ports/LeagueRepository';
import { LeagueEventPublisher, LeagueAccessedEvent } from '../ports/LeagueEventPublisher';

export interface GetLeagueQuery {
  leagueId: string;
  driverId?: string;
}

export class GetLeagueUseCase {
  constructor(
    private readonly leagueRepository: LeagueRepository,
    private readonly eventPublisher: LeagueEventPublisher,
  ) {}

  async execute(query: GetLeagueQuery): Promise<LeagueData> {
    // Validate query
    if (!query.leagueId || query.leagueId.trim() === '') {
      throw new Error('League ID is required');
    }

    // Find league
    const league = await this.leagueRepository.findById(query.leagueId);
    if (!league) {
      throw new Error(`League with id ${query.leagueId} not found`);
    }

    // Emit event if driver ID is provided
    if (query.driverId) {
      const event: LeagueAccessedEvent = {
        type: 'LeagueAccessedEvent',
        leagueId: query.leagueId,
        driverId: query.driverId,
        timestamp: new Date(),
      };
      await this.eventPublisher.emitLeagueAccessed(event);
    }

    return league;
  }
}
