import { useQuery } from '@tanstack/react-query';
import { useInject } from '@/lib/di/hooks/useInject';
import { LEAGUE_MEMBERSHIP_SERVICE_TOKEN } from '@/lib/di/tokens';
import { LeagueRoleUtility } from '@/lib/utilities/LeagueRoleUtility';
import { enhanceQueryResult } from '@/lib/di/hooks/useReactQueryWithApiError';

export function useLeagueAdminStatus(leagueId: string, currentDriverId: string) {
  const leagueMembershipService = useInject(LEAGUE_MEMBERSHIP_SERVICE_TOKEN);

  const queryResult = useQuery({
    queryKey: ['leagueMembership', leagueId, currentDriverId],
    queryFn: async () => {
      await leagueMembershipService.fetchLeagueMemberships(leagueId);
      const membership = leagueMembershipService.getMembership(leagueId, currentDriverId);
      return membership ? LeagueRoleUtility.isLeagueAdminOrHigherRole(membership.role) : false;
    },
    enabled: !!leagueId && !!currentDriverId,
  });

  return enhanceQueryResult(queryResult);
}