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

export class LeagueRulebookPageQuery implements PageQuery<RulebookViewData, string, PresentationError> {
  async execute(leagueId: string): Promise<Result<RulebookViewData, PresentationError>> {
    const service = new LeagueRulebookService();
    const result = await service.getRulebookData(leagueId);

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

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

  static async execute(leagueId: string): Promise<Result<RulebookViewData, PresentationError>> {
    const query = new LeagueRulebookPageQuery();
    return query.execute(leagueId);
  }
}
