import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { valuationApi, type ValuationRequest } from '@/lib/valuation-api';

export const valuationKeys = {
  all: ['valuation'] as const,
  history: (page: number) => ['valuation', 'history', page] as const,
  detail: (id: string) => ['valuation', 'detail', id] as const,
};

export function useValuationPredict() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: ValuationRequest) => valuationApi.predict(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: valuationKeys.all });
    },
  });
}

export function useValuationPredictForListing() {
  return useMutation({
    mutationFn: (listingId: string) => valuationApi.predictForListing(listingId),
  });
}

export function useValuationHistory(page = 1) {
  return useQuery({
    queryKey: valuationKeys.history(page),
    queryFn: () => valuationApi.getHistory(page),
  });
}

export function useValuationDetail(id: string) {
  return useQuery({
    queryKey: valuationKeys.detail(id),
    queryFn: () => valuationApi.getById(id),
    enabled: !!id,
  });
}
