import { Result } from '@/lib/contracts/Result';
import type { PageQuery } from '@/lib/contracts/page-queries/PageQuery';
import { SessionGateway } from '@/lib/gateways/SessionGateway';
import { SponsorshipRequestsService } from '@/lib/services/sponsors/SponsorshipRequestsService';
import { SponsorshipRequestsPageViewDataBuilder } from '@/lib/builders/view-data/SponsorshipRequestsPageViewDataBuilder';
import type { SponsorshipRequestsViewData } from '@/lib/view-data/SponsorshipRequestsViewData';
import { mapToPresentationError, type PresentationError } from '@/lib/contracts/page-queries/PresentationError';

/**
 * Sponsorship Requests Page Query
 * 
 * Server-side composition that:
 * 1. Reads session to determine currentDriverId
 * 2. Uses service for orchestration
 * 3. Transforms to ViewData using builder
 * 4. Returns Result<ViewData, PresentationError>
 */
export class SponsorshipRequestsPageQuery implements PageQuery<SponsorshipRequestsViewData, void, PresentationError> {
  async execute(): Promise<Result<SponsorshipRequestsViewData, PresentationError>> {
    // Get session to determine current driver
    const sessionGateway = new SessionGateway();
    const session = await sessionGateway.getSession();
    
    if (!session?.user?.primaryDriverId) {
      return Result.err('notFound');
    }
    
    const service = new SponsorshipRequestsService();
    const serviceResult = await service.getPendingRequests({
      entityType: 'driver',
      entityId: session.user.primaryDriverId,
    });

    if (serviceResult.isErr()) {
      return Result.err(mapToPresentationError(serviceResult.getError()));
    }

    // Transform to ViewData using builder
    const apiDto = serviceResult.unwrap();
    const sponsorshipView = SponsorshipRequestsPageViewDataBuilder.build(apiDto);
    return Result.ok(sponsorshipView);
  }

  static async execute(): Promise<Result<SponsorshipRequestsViewData, PresentationError>> {
    const query = new SponsorshipRequestsPageQuery();
    return query.execute();
  }
}
