import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { rateLimitService } from '@/services/rateLimitService'
import type { RateLimitRule } from '@/types/api'

export function useRateLimits() {
  return useQuery({
    queryKey: ['ratelimit'],
    queryFn: rateLimitService.getAll,
    placeholderData: (previousData) => previousData,
  })
}

export function useCreateRateLimit() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: Partial<RateLimitRule>) => rateLimitService.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['ratelimit'] })
    },
  })
}

export function useUpdateRateLimit() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: Partial<RateLimitRule> }) => rateLimitService.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['ratelimit'] })
    },
  })
}

export function useDeleteRateLimit() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: rateLimitService.delete,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['ratelimit'] })
    },
  })
}
