import { SponsorsApiClient } from '@/lib/api/sponsors/SponsorsApiClient';
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
import { isProductionEnvironment } from '@/lib/config/env';
import { Result } from '@/lib/contracts/Result';
import type { Service, DomainError } from '@/lib/contracts/services/Service';
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';

export interface PendingSponsorshipRequestDto {
  requestId: string;
  sponsorId: string;
  sponsorName: string;
  message: string | null;
  createdAtIso: string;
}

export interface SponsorshipRequestsReadApiDto {
  sections: Array<{
    entityType: 'driver' | 'team' | 'season';
    entityId: string;
    entityName: string;
    requests: PendingSponsorshipRequestDto[];
  }>;
}

export class SponsorshipRequestsReadService implements Service {
  private readonly client: SponsorsApiClient;

  constructor() {
    const baseUrl = getWebsiteApiBaseUrl();
    const logger = new ConsoleLogger();
    const errorReporter = new EnhancedErrorReporter(logger, {
      showUserNotifications: true,
      logToConsole: true,
      reportToExternal: isProductionEnvironment(),
    });

    this.client = new SponsorsApiClient(baseUrl, errorReporter, logger);
  }

  async getPendingRequestsForDriver(
    driverId: string,
  ): Promise<Result<SponsorshipRequestsReadApiDto, DomainError>> {
    try {
      const response = await this.client.getPendingSponsorshipRequests({
        entityType: 'driver',
        entityId: driverId,
      });

      const requests = (response.requests ?? []).map((r) => {
        const raw = r as unknown as {
          id?: string;
          requestId?: string;
          sponsorId?: string;
          sponsorName?: string;
          message?: unknown;
          createdAt?: string;
          createdAtIso?: string;
        };

        return {
          requestId: String(raw.id ?? raw.requestId ?? ''),
          sponsorId: String(raw.sponsorId ?? ''),
          sponsorName: String(raw.sponsorName ?? 'Sponsor'),
          message: typeof raw.message === 'string' ? raw.message : null,
          createdAtIso: String(raw.createdAt ?? raw.createdAtIso ?? ''),
        };
      });

      return Result.ok({
        sections: [
          {
            entityType: 'driver',
            entityId: driverId,
            entityName: 'Your Profile',
            requests,
          },
        ],
      });
    } catch (error: any) {
      const errorAny = error as { statusCode?: number; message?: string };
      if (errorAny.statusCode === 401) return Result.err({ type: 'unauthorized', message: 'Unauthorized' });
      if (errorAny.statusCode === 404) return Result.err({ type: 'notFound', message: 'Not found' });
      return Result.err({ type: 'serverError', message: error.message || 'Server error' });
    }
  }
}
