import { injectable, unmanaged } from 'inversify';
import { SponsorsApiClient } from '@/lib/api/sponsors/SponsorsApiClient';
import { SponsorshipPricingViewModel } from '@/lib/view-models/SponsorshipPricingViewModel';
import { SponsorSponsorshipsViewModel } from '@/lib/view-models/SponsorSponsorshipsViewModel';
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
import { Service } from '@/lib/contracts/services/Service';

@injectable()
export class SponsorshipService implements Service {
  private readonly apiClient: SponsorsApiClient;

  constructor(@unmanaged() apiClient?: SponsorsApiClient) {
    if (apiClient) {
      this.apiClient = apiClient;
    } else {
      const baseUrl = getWebsiteApiBaseUrl();
      const logger = new ConsoleLogger();
      const errorReporter = new EnhancedErrorReporter(logger);
      this.apiClient = new SponsorsApiClient(baseUrl, errorReporter, logger);
    }
  }

  async getSponsorshipPricing(leagueId?: string): Promise<SponsorshipPricingViewModel> {
    const data = await this.apiClient.getPricing();
    // Map the array-based pricing to the expected view model format
    const mainSlot = data.pricing.find(p => p.entityType === 'league');
    const secondarySlot = data.pricing.find(p => p.entityType === 'driver');
    
    return new SponsorshipPricingViewModel({
      mainSlotPrice: mainSlot?.price || 0,
      secondarySlotPrice: secondarySlot?.price || 0,
      currency: 'USD' // Default currency as it's missing from API
    });
  }

  async getSponsorSponsorships(sponsorId: string): Promise<SponsorSponsorshipsViewModel | null> {
    const data = await this.apiClient.getSponsorships(sponsorId);
    if (!data) return null;
    return new SponsorSponsorshipsViewModel(data);
  }
}
