import { useQuery, UseQueryOptions } from '@tanstack/react-query';
import { useInject } from '@/lib/di/hooks/useInject';
import { LEAGUE_SERVICE_TOKEN } from '@/lib/di/tokens';
import { ApiError } from '@/lib/api/base/ApiError';
import type { LeagueWithCapacityAndScoringDTO } from '@/lib/types/generated/LeagueWithCapacityAndScoringDTO';
import type { LeagueMembershipsDTO } from '@/lib/types/generated/LeagueMembershipsDTO';
import type { AllLeaguesWithCapacityAndScoringDTO } from '@/lib/types/AllLeaguesWithCapacityAndScoringDTO';

interface UseLeagueDetailOptions {
  leagueId: string;
  queryOptions?: UseQueryOptions<LeagueWithCapacityAndScoringDTO, ApiError>;
}

interface UseLeagueMembershipsOptions {
  leagueId: string;
  queryOptions?: UseQueryOptions<LeagueMembershipsDTO, ApiError>;
}

export function useLeagueDetail({ leagueId, queryOptions }: UseLeagueDetailOptions) {
  const leagueService = useInject(LEAGUE_SERVICE_TOKEN);

  return useQuery<LeagueWithCapacityAndScoringDTO, ApiError>({
    queryKey: ['league-detail', leagueId],
    queryFn: async () => {
      const result = await leagueService.getAllLeagues();
      if (result.isErr()) {
        throw result.getError();
      }
      const data = result.unwrap();
      // Filter for the specific league
      const leagues = Array.isArray(data?.leagues) ? data.leagues : [];
      const league = leagues.find(l => l.id === leagueId);
      if (!league) {
        throw new ApiError('League not found', 'NOT_FOUND', {
          endpoint: 'getAllLeagues',
          statusCode: 404,
          timestamp: new Date().toISOString()
        });
      }
      return league;
    },
    ...queryOptions,
  });
}

export function useLeagueMemberships({ leagueId, queryOptions }: UseLeagueMembershipsOptions) {
  const leagueService = useInject(LEAGUE_SERVICE_TOKEN);

  return useQuery<LeagueMembershipsDTO, ApiError>({
    queryKey: ['league-memberships', leagueId],
    queryFn: async () => {
      const result = await leagueService.getLeagueMemberships(leagueId);
      if (result.isErr()) {
        throw result.getError();
      }
      // The DTO already has the correct structure with members property
      return result.unwrap();
    },
    ...queryOptions,
  });
}