import { Result } from '@/lib/contracts/Result';
import { Service, DomainError } from '@/lib/contracts/services/Service';
import { RulebookApiDto } from '@/lib/types/tbd/RulebookApiDto';
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 LeagueRulebookService implements Service {
  private apiClient: LeaguesApiClient;

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

  async getRulebookData(leagueId: string): Promise<Result<RulebookApiDto, DomainError>> {
    try {
      const config = await this.apiClient.getLeagueConfig(leagueId);
      
      const mockData: RulebookApiDto = {
        leagueId,
        scoringConfig: {
          gameName: 'iRacing',
          scoringPresetName: config.form?.scoring?.type || 'Standard',
          championships: (config.form?.championships || []).map((c: any) => ({
            type: c.type || 'driver',
            sessionTypes: ['Race'],
            pointsPreview: [],
            bonusSummary: [],
          })),
          dropPolicySummary: config.form?.dropPolicy?.strategy || 'All results count',
        },
      };
      return Result.ok(mockData);
    } catch (error: unknown) {
      return Result.err({ type: 'serverError', message: (error as Error).message || 'Failed to fetch rulebook' });
    }
  }
}
