import { Result } from '@/lib/contracts/Result';
import { PageQuery } from '@/lib/contracts/page-queries/PageQuery';
import { LeagueStewardingService } from '@/lib/services/leagues/LeagueStewardingService';
import { StewardingViewDataBuilder } from '@/lib/builders/view-data/StewardingViewDataBuilder';
import { StewardingViewData } from '@/lib/view-data/leagues/StewardingViewData';
import { type PresentationError, mapToPresentationError } from '@/lib/contracts/page-queries/PresentationError';

export class LeagueStewardingPageQuery implements PageQuery<StewardingViewData, string, PresentationError> {
  async execute(leagueId: string): Promise<Result<StewardingViewData, PresentationError>> {
    const service = new LeagueStewardingService();
    const result = await service.getStewardingData(leagueId);

    if (result.isErr()) {
      // Map domain errors to presentation errors
      return Result.err(mapToPresentationError(result.getError()));
    }

    const viewData = StewardingViewDataBuilder.build(result.unwrap());
    return Result.ok(viewData);
  }

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