import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { savedSearchApi, type CreateSavedSearchPayload, type UpdateSavedSearchPayload } from '@/lib/saved-search-api';

export const savedSearchKeys = {
  all: ['savedSearches'] as const,
  list: (params?: { page?: number; limit?: number }) => ['savedSearches', 'list', params] as const,
  detail: (id: string) => ['savedSearches', 'detail', id] as const,
};

export function useSavedSearches(params?: { page?: number; limit?: number }) {
  return useQuery({
    queryKey: savedSearchKeys.list(params),
    queryFn: () => savedSearchApi.list(params),
  });
}

export function useSavedSearchDetail(id: string) {
  return useQuery({
    queryKey: savedSearchKeys.detail(id),
    queryFn: () => savedSearchApi.getById(id),
    enabled: !!id,
  });
}

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

  return useMutation({
    mutationFn: (data: CreateSavedSearchPayload) => savedSearchApi.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: savedSearchKeys.all });
    },
  });
}

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

  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: UpdateSavedSearchPayload }) =>
      savedSearchApi.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: savedSearchKeys.all });
    },
  });
}

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

  return useMutation({
    mutationFn: (id: string) => savedSearchApi.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: savedSearchKeys.all });
    },
  });
}
