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 { Service, DomainError } from '@/lib/contracts/services/Service';
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
import type { GetPendingSponsorshipRequestsOutputDTO } from '@/lib/types/generated/GetPendingSponsorshipRequestsOutputDTO';
import type { AcceptSponsorshipRequestInputDTO } from '@/lib/types/generated/AcceptSponsorshipRequestInputDTO';
import type { RejectSponsorshipRequestInputDTO } from '@/lib/types/generated/RejectSponsorshipRequestInputDTO';

interface GetPendingRequestsInput {
  entityType: string;
  entityId: string;
}

export class SponsorshipRequestsService 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 getPendingRequests(
    input: GetPendingRequestsInput,
  ): Promise<Result<GetPendingSponsorshipRequestsOutputDTO, DomainError>> {
    try {
      const result = await this.client.getPendingSponsorshipRequests({
        entityType: input.entityType,
        entityId: input.entityId,
      });

      return Result.ok(result);
    } catch {
      return Result.err({ type: 'serverError', message: 'Failed to fetch pending requests' });
    }
  }

  async acceptRequest(
    command: { requestId: string; actorDriverId: string },
  ): Promise<Result<void, DomainError>> {
    try {
      const input: AcceptSponsorshipRequestInputDTO = {
        respondedBy: command.actorDriverId,
      };
      await this.client.acceptSponsorshipRequest(command.requestId, input);

      return Result.ok(undefined);
    } catch {
      return Result.err({ type: 'serverError', message: 'Failed to accept sponsorship request' });
    }
  }

  async rejectRequest(
    command: { requestId: string; actorDriverId: string; reason: string | null },
  ): Promise<Result<void, DomainError>> {
    try {
      const input: RejectSponsorshipRequestInputDTO = {
        respondedBy: command.actorDriverId,
        reason: command.reason || undefined,
      };
      await this.client.rejectSponsorshipRequest(command.requestId, input);

      return Result.ok(undefined);
    } catch {
      return Result.err({ type: 'serverError', message: 'Failed to reject sponsorship request' });
    }
  }
}
