import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { usageApi } from "../lib/api/usage";
import { useAuthStore } from "../stores/authStore";

const balanceKey = () => ["usage-balance"];
const recordsKey = (limit: number, offset: number) => ["usage-records", limit, offset];
const costsKey = () => ["usage-costs"];

export function useBalance() {
  const isAuthReady = useAuthStore((state) => state.hasHydrated && state.isAuthenticated);
  return useQuery({
    queryKey: balanceKey(),
    queryFn: () => usageApi.getBalance(),
    staleTime: 30_000,
    enabled: isAuthReady,
  });
}

export function useRecords(limit = 20, offset = 0) {
  const isAuthReady = useAuthStore((state) => state.hasHydrated && state.isAuthenticated);
  return useQuery({
    queryKey: recordsKey(limit, offset),
    queryFn: () => usageApi.getRecords(limit, offset),
    staleTime: 30_000,
    enabled: isAuthReady,
  });
}

export function useCosts() {
  const isAuthReady = useAuthStore((state) => state.hasHydrated && state.isAuthenticated);
  return useQuery({
    queryKey: costsKey(),
    queryFn: () => usageApi.getCosts(),
    staleTime: 5 * 60_000,
    enabled: isAuthReady,
  });
}

export function useOperationCost(operation: string): number | null {
  const { data } = useCosts();
  if (!data) return null;
  const raw = data[operation];
  if (raw == null) return null;
  const n = Number(raw);
  return Number.isFinite(n) ? n : null;
}

export function usePurchase() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (packageId: string) => usageApi.purchase(packageId),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: balanceKey() });
      qc.invalidateQueries({ queryKey: ["usage-records"] });
    },
  });
}
