import type { SponsorsApiClient } from '../../api/sponsors/SponsorsApiClient';
import { SponsorshipPricingViewModel } from '../../view-models/SponsorshipPricingViewModel';
import { SponsorSponsorshipsViewModel } from '../../view-models/SponsorSponsorshipsViewModel';
import { SponsorshipRequestViewModel } from '../../view-models/SponsorshipRequestViewModel';
import type { GetPendingSponsorshipRequestsOutputDTO } from '../../types/generated/GetPendingSponsorshipRequestsOutputDTO';
import type { SponsorshipRequestDTO } from '../../types/generated/SponsorshipRequestDTO';

/**
 * Sponsorship Service
 *
 * Orchestrates sponsorship operations by coordinating API calls and view model creation.
 * All dependencies are injected via constructor.
 */
export class SponsorshipService {
  constructor(
    private readonly apiClient: SponsorsApiClient
  ) {}

  /**
   * Get sponsorship pricing with view model transformation
   */
  async getSponsorshipPricing(): Promise<SponsorshipPricingViewModel> {
    // Pricing shape isn't finalized in the API yet.
    // Keep a predictable, UI-friendly structure until a dedicated DTO is introduced.
    const dto = await this.apiClient.getPricing();

    const main =
      dto.pricing.find((p) => p.entityType === 'league' || p.entityType === 'main')?.price ?? 0;
    const secondary =
      dto.pricing.find((p) => p.entityType === 'driver' || p.entityType === 'secondary')?.price ?? 0;

    return new SponsorshipPricingViewModel({
      mainSlotPrice: main,
      secondarySlotPrice: secondary,
      currency: 'USD',
    });
  }

  /**
    * Get sponsor sponsorships with view model transformation
    */
  async getSponsorSponsorships(sponsorId: string): Promise<SponsorSponsorshipsViewModel | null> {
    const dto = await this.apiClient.getSponsorships(sponsorId);
    if (!dto) {
      return null;
    }
    return new SponsorSponsorshipsViewModel(dto);
  }

  /**
   * Get pending sponsorship requests for an entity
   */
  async getPendingSponsorshipRequests(params: { entityType: string; entityId: string }): Promise<SponsorshipRequestViewModel[]> {
    const dto = (await this.apiClient.getPendingSponsorshipRequests(params)) as unknown as GetPendingSponsorshipRequestsOutputDTO;
    const requests = (dto as any).requests as SponsorshipRequestDTO[];
    return (requests ?? []).map((r: SponsorshipRequestDTO) => new SponsorshipRequestViewModel(r));
  }

  /**
   * Accept a sponsorship request
   */
  async acceptSponsorshipRequest(requestId: string, respondedBy: string): Promise<void> {
    await this.apiClient.acceptSponsorshipRequest(requestId, { respondedBy });
  }

  /**
   * Reject a sponsorship request
   */
  async rejectSponsorshipRequest(requestId: string, respondedBy: string, reason?: string): Promise<void> {
    await this.apiClient.rejectSponsorshipRequest(requestId, { respondedBy, ...(reason ? { reason } : {}) });
  }
}
