import { Result } from '@/lib/contracts/Result';
import { Service, DomainError } from '@/lib/contracts/services/Service';
import { LeagueScheduleApiDto } from '@/lib/types/tbd/LeagueScheduleApiDto';
import { LeaguesApiClient } from '@/lib/api/leagues/LeaguesApiClient';
import { ConsoleErrorReporter } from '@/lib/infrastructure/logging/ConsoleErrorReporter';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';

export class LeagueScheduleService implements Service {
  private apiClient: LeaguesApiClient;

  constructor() {
    const baseUrl = getWebsiteApiBaseUrl();
    this.apiClient = new LeaguesApiClient(
      baseUrl,
      new ConsoleErrorReporter(),
      new ConsoleLogger()
    );
  }

  async getScheduleData(leagueId: string): Promise<Result<LeagueScheduleApiDto, DomainError>> {
    try {
      const data = await this.apiClient.getSchedule(leagueId);
      
      // Map LeagueScheduleDTO to LeagueScheduleApiDto
      const apiDto: LeagueScheduleApiDto = {
        leagueId,
        races: data.races.map(race => ({
          id: race.id,
          name: race.name,
          date: race.date,
          track: (race as any).track || 'TBA',
          car: (race as any).car || 'TBA',
          sessionType: (race as any).sessionType || 'Race',
          status: (race as any).status || 'scheduled',
          strengthOfField: (race as any).strengthOfField,
        })),
      };
      
      return Result.ok(apiDto);
    } catch (error: unknown) {
      return Result.err({ type: 'serverError', message: (error as Error).message || 'Failed to fetch schedule' });
    }
  }
}
