/**
 * Saved filters API hooks — CRUD for reusable filter criteria.
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiGet, apiPost, apiDelete } from './client';

export interface SavedFilter {
  id: string;
  name: string;
  entity_type: string;
  filter_criteria: Record<string, any>;
  user_id: string;
  created_at: string;
  updated_at: string;
}

export interface SavedFilterCreateInput {
  name: string;
  entity_type: string;
  filter_criteria: Record<string, any>;
}

export function useSavedFilters(entityType?: string) {
  const params = new URLSearchParams();
  if (entityType) params.set('entity_type', entityType);
  return useQuery({
    queryKey: ['saved-filters', entityType],
    queryFn: () => apiGet<SavedFilter[]>(`/saved-filters?${params.toString()}`),
  });
}

export function useCreateSavedFilter() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (data: SavedFilterCreateInput) => apiPost<SavedFilter>('/saved-filters', data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['saved-filters'] });
    },
  });
}

export function useDeleteSavedFilter() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => apiDelete(`/saved-filters/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['saved-filters'] });
    },
  });
}
