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

export function useSkills(resumeId?: string) {
    return useQuery({
        queryKey: ["skills", resumeId],
        queryFn: () => skillService.getAll(resumeId),
    })
}

export function useSkill(id: string) {
    return useQuery({
        queryKey: ["skill", id],
        queryFn: () => skillService.getById(id),
        enabled: !!id,
    })
}

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

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

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

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

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

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