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

export function useCorsRules(type: 'whitelist' | 'blacklist', page = 1, limit = 10) {
    return useQuery({
        queryKey: ['cors', type, page, limit],
        queryFn: () => corsService.getAll(type, page, limit),
        placeholderData: (previousData) => previousData,
    })
}

export function useCreateCorsRule(type: 'whitelist' | 'blacklist') {
    const queryClient = useQueryClient()
    return useMutation({
        mutationFn: (data: Partial<CorsRule>) => corsService.create(type, data),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['cors', type] })
        },
    })
}

export function useUpdateCorsRule(type: 'whitelist' | 'blacklist') {
    const queryClient = useQueryClient()
    return useMutation({
        mutationFn: ({ id, data }: { id: string; data: Partial<CorsRule> }) => corsService.update(type, id, data),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['cors', type] })
        },
    })
}

export function useDeleteCorsRule(type: 'whitelist' | 'blacklist') {
    const queryClient = useQueryClient()
    return useMutation({
        mutationFn: (id: string) => corsService.delete(type, id),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['cors', type] })
        },
    })
}
