import { useQuery, useMutation } from "@tanstack/react-query";
import type { SportType } from "@/lib/api/matches/types";
import { predictionsService } from "./service";
import type { SmartCouponRequestDto } from "./types";

export const PredictionsQueryKeys = {
  all: ["predictions"] as const,
  detail: (matchId: string) =>
    [...PredictionsQueryKeys.all, "detail", matchId] as const,
  commentary: (matchId: string) =>
    [...PredictionsQueryKeys.all, "commentary", matchId] as const,
  upcoming: () => [...PredictionsQueryKeys.all, "upcoming"] as const,
  valueBets: () => [...PredictionsQueryKeys.all, "valueBets"] as const,
  history: () => [...PredictionsQueryKeys.all, "history"] as const,
  health: () => [...PredictionsQueryKeys.all, "health"] as const,
};

export const usePrediction = (matchId: string) => {
  return useQuery({
    queryKey: PredictionsQueryKeys.detail(matchId),
    queryFn: () => predictionsService.getPrediction(matchId),
    enabled: false, // DO NOT auto-fetch since it consumes limits
  });
};

export const useAiCommentary = (matchId: string, enabled: boolean) => {
  return useQuery({
    queryKey: PredictionsQueryKeys.commentary(matchId),
    queryFn: () => predictionsService.getCommentary(matchId),
    enabled,
    staleTime: 10 * 60 * 1000, // 10 dakika cache
    retry: 1,
  });
};

export const useGeneratePrediction = () => {
  return useMutation({
    mutationFn: (body: { matchId: string; sport?: SportType }) =>
      predictionsService.generatePrediction(body),
  });
};

export const useUpcomingPredictions = () => {
  return useQuery({
    queryKey: PredictionsQueryKeys.upcoming(),
    queryFn: () => predictionsService.getUpcoming(),
  });
};

export const useValueBets = () => {
  return useQuery({
    queryKey: PredictionsQueryKeys.valueBets(),
    queryFn: () => predictionsService.getValueBets(),
  });
};

export const usePredictionHistory = () => {
  return useQuery({
    queryKey: PredictionsQueryKeys.history(),
    queryFn: () => predictionsService.getHistory(),
  });
};

export const useAIHealth = () => {
  return useQuery({
    queryKey: PredictionsQueryKeys.health(),
    queryFn: () => predictionsService.checkHealth(),
    refetchInterval: 30_000, // Auto-refresh every 30s
  });
};

export const useGenerateSmartCoupon = () => {
  return useMutation({
    mutationFn: (body: SmartCouponRequestDto) =>
      predictionsService.generateSmartCoupon(body),
  });
};
