import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { knowledgeService } from "@/services/knowledgeService"
import { showToast } from "@/lib/sweetalert"

export function useKnowledges(resumeId?: string) {
    return useQuery({
        queryKey: ["knowledges", resumeId],
        queryFn: () => knowledgeService.getAll(resumeId),
    })
}

export function useKnowledge(id: string) {
    return useQuery({
        queryKey: ["knowledge", id],
        queryFn: () => knowledgeService.getById(id),
        enabled: !!id,
    })
}

export function useCreateKnowledge() {
    const queryClient = useQueryClient()

    return useMutation({
        mutationFn: knowledgeService.create,
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["knowledges"] })
            showToast.success("Bilgi başarıyla eklendi", "İşlem Başarılı")
        },
        onError: (error: any) => {
            showToast.error(error.response?.data?.error || "Bilgi eklenirken bir hata oluştu", "Hata")
        },
    })
}

export function useUpdateKnowledge() {
    const queryClient = useQueryClient()

    return useMutation({
        mutationFn: ({ id, data }: { id: string; data: any }) =>
            knowledgeService.update(id, data),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["knowledges"] })
            showToast.success("Bilgi başarıyla güncellendi", "İşlem Başarılı")
        },
        onError: (error: any) => {
            showToast.error(error.response?.data?.error || "Bilgi güncellenirken bir hata oluştu", "Hata")
        },
    })
}

export function useDeleteKnowledge() {
    const queryClient = useQueryClient()

    return useMutation({
        mutationFn: knowledgeService.delete,
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["knowledges"] })
            showToast.success("Bilgi başarıyla silindi", "İşlem Başarılı")
        },
        onError: (error: any) => {
            showToast.error(error.response?.data?.error || "Bilgi silinirken bir hata oluştu", "Hata")
        },
    })
}
