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

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

export function useBalance() {
  return useQuery({
    queryKey: balanceKey(),
    queryFn: () => usageApi.getBalance(),
    staleTime: 30_000,
  });
}

export function useRecords(limit = 20, offset = 0) {
  return useQuery({
    queryKey: recordsKey(limit, offset),
    queryFn: () => usageApi.getRecords(limit, offset),
    staleTime: 30_000,
  });
}

export function useCosts() {
  return useQuery({
    queryKey: costsKey(),
    queryFn: () => usageApi.getCosts(),
    staleTime: 5 * 60_000,
  });
}

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"] });
    },
  });
}
