import { PageQuery } from '@/lib/contracts/page-queries/PageQuery';
import { Result } from '@/lib/contracts/Result';
import { LeaderboardsViewDataBuilder } from '@/lib/builders/view-data/LeaderboardsViewDataBuilder';
import type { LeaderboardsViewData } from '@/lib/view-data/LeaderboardsViewData';
import { LeaderboardsService } from '@/lib/services/leaderboards/LeaderboardsService';
import { mapToPresentationError, type PresentationError } from '@/lib/contracts/page-queries/PresentationError';

/**
 * Leaderboards page query
 * Returns Result<LeaderboardsViewData, PresentationError>
 * No DI container usage - constructs dependencies explicitly
 */
export class LeaderboardsPageQuery implements PageQuery<LeaderboardsViewData, void, PresentationError> {
  async execute(): Promise<Result<LeaderboardsViewData, PresentationError>> {
    // Manual wiring: Service creates its own dependencies
    const service = new LeaderboardsService();
    
    // Fetch data using service
    const serviceResult = await service.getLeaderboards();
    
    if (serviceResult.isErr()) {
      // Map domain errors to presentation errors
      return Result.err(mapToPresentationError(serviceResult.getError()));
    }

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

  // Static method to avoid object construction in server code
  static async execute(): Promise<Result<LeaderboardsViewData, PresentationError>> {
    const query = new LeaderboardsPageQuery();
    return query.execute();
  }
}