import { useQuery } from "@tanstack/react-query";
import { leaguesService } from "./service";
import type {
  LeagueQueryParams,
  TeamSearchParams,
  HeadToHeadParams,
  TeamMatchesParams,
} from "./types";

export const LeaguesQueryKeys = {
  all: ["leagues"] as const,
  list: (params?: LeagueQueryParams) =>
    [...LeaguesQueryKeys.all, "list", params] as const,
  detail: (id: string) => [...LeaguesQueryKeys.all, "detail", id] as const,
  countries: () => [...LeaguesQueryKeys.all, "countries"] as const,
  country: (id: string) => [...LeaguesQueryKeys.all, "country", id] as const,
  team: (id: string) => [...LeaguesQueryKeys.all, "team", id] as const,
  teamMatches: (id: string, params?: TeamMatchesParams) =>
    [...LeaguesQueryKeys.all, "teamMatches", id, params] as const,
  headToHead: (params: HeadToHeadParams) =>
    [...LeaguesQueryKeys.all, "h2h", params] as const,
  searchTeams: (params: TeamSearchParams) =>
    [...LeaguesQueryKeys.all, "searchTeams", params] as const,
};

export const useLeagues = (params?: LeagueQueryParams) => {
  return useQuery({
    queryKey: LeaguesQueryKeys.list(params),
    queryFn: () => leaguesService.getLeagues(params),
  });
};

export const useLeagueById = (id: string) => {
  return useQuery({
    queryKey: LeaguesQueryKeys.detail(id),
    queryFn: () => leaguesService.getLeagueById(id),
    enabled: !!id,
  });
};

export const useCountries = () => {
  return useQuery({
    queryKey: LeaguesQueryKeys.countries(),
    queryFn: () => leaguesService.getCountries(),
  });
};

export const useCountryById = (id: string) => {
  return useQuery({
    queryKey: LeaguesQueryKeys.country(id),
    queryFn: () => leaguesService.getCountryById(id),
    enabled: !!id,
  });
};

export const useTeamById = (id: string) => {
  return useQuery({
    queryKey: LeaguesQueryKeys.team(id),
    queryFn: () => leaguesService.getTeamById(id),
    enabled: !!id,
  });
};

export const useTeamMatches = (id: string, params?: TeamMatchesParams) => {
  return useQuery({
    queryKey: LeaguesQueryKeys.teamMatches(id, params),
    queryFn: () => leaguesService.getTeamMatches(id, params),
    enabled: !!id,
  });
};

export const useHeadToHead = (params: HeadToHeadParams) => {
  return useQuery({
    queryKey: LeaguesQueryKeys.headToHead(params),
    queryFn: () => leaguesService.getHeadToHead(params),
    enabled: !!params.team1 && !!params.team2,
  });
};

export const useSearchTeams = (params: TeamSearchParams) => {
  return useQuery({
    queryKey: LeaguesQueryKeys.searchTeams(params),
    queryFn: () => leaguesService.searchTeams(params),
    enabled: params.q.length >= 2,
  });
};
