import { Result } from '@/lib/contracts/Result';
import type { PageQuery } from '@/lib/contracts/page-queries/PageQuery';
import { SessionGateway } from '@/lib/gateways/SessionGateway';
import { ProfileLeaguesService } from '@/lib/services/leagues/ProfileLeaguesService';
import { ProfileLeaguesViewDataBuilder } from '@/lib/builders/view-data/ProfileLeaguesViewDataBuilder';
import type { ProfileLeaguesViewData } from '@/lib/view-data/ProfileLeaguesViewData';
import { mapToPresentationError, type PresentationError } from '@/lib/contracts/page-queries/PresentationError';

/**
 * Profile Leagues 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 ProfileLeaguesPageQuery implements PageQuery<ProfileLeaguesViewData, void, PresentationError> {
  async execute(): Promise<Result<ProfileLeaguesViewData, PresentationError>> {
    // Get session server-side
    const sessionGateway = new SessionGateway();
    const session = await sessionGateway.getSession();
    
    if (!session?.user?.primaryDriverId) {
      return Result.err('notFound');
    }
    
    const currentDriverId = session.user.primaryDriverId;
    const service = new ProfileLeaguesService();
    const serviceResult = await service.getProfileLeagues(currentDriverId);

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

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

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