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

export class LeagueStandingsPageQuery implements PageQuery<LeagueStandingsViewData, string, PresentationError> {
  async execute(leagueId: string): Promise<Result<LeagueStandingsViewData, PresentationError>> {
    const service = new LeagueStandingsService();
    const result = await service.getStandingsData(leagueId);

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

    const { standings, memberships } = result.unwrap();
    const viewData = LeagueStandingsViewDataBuilder.build(standings, memberships, leagueId);
    return Result.ok(viewData);
  }

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