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

export function useTags(page = 1, limit = 10) {
    return useQuery({
        queryKey: ['tags', page, limit],
        queryFn: () => tagService.getAll(page, limit),
        placeholderData: (previousData) => previousData,
    })
}

export function useTag(id: string) {
    return useQuery({
        queryKey: ['tag', id],
        queryFn: () => tagService.getById(id),
        enabled: !!id,
    })
}

export function useCreateTag() {
    const queryClient = useQueryClient()
    return useMutation({
        mutationFn: tagService.create,
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['tags'] })
        },
    })
}

export function useUpdateTag() {
    const queryClient = useQueryClient()
    return useMutation({
        mutationFn: ({ id, data }: { id: string; data: Partial<Tag> }) => tagService.update(id, data),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['tags'] })
        },
    })
}

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