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

/**
 * LeagueScheduleAdminPageQuery
 * 
 * Fetches league schedule admin data.
 */
export class LeagueScheduleAdminPageQuery implements PageQuery<unknown, { leagueId: string; seasonId?: string }> {
  async execute(input: { leagueId: string; seasonId?: string }): Promise<Result<unknown, PresentationError>> {
    const service = new LeagueService();
    const result = await service.getScheduleAdminData(input.leagueId, input.seasonId);

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

    const data = result.unwrap();
    const viewData = LeagueScheduleViewDataBuilder.build({
      leagueId: data.leagueId,
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      races: data.schedule.races.map((r: any) => ({
        id: r.id,
        name: r.name,
        date: r.scheduledAt,
        track: r.track,
        car: r.car,
        sessionType: r.sessionType,
      })),
    });
    return Result.ok(viewData);
  }

  static async execute(input: { leagueId: string; seasonId?: string }): Promise<Result<unknown, PresentationError>> {
    const query = new LeagueScheduleAdminPageQuery();
    return query.execute(input);
  }
}
