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

export function useEducations(resumeId?: string) {
    return useQuery({
        queryKey: ["educations", resumeId],
        queryFn: () => educationService.getAll(resumeId),
    })
}

export function useEducation(id: string) {
    return useQuery({
        queryKey: ["education", id],
        queryFn: () => educationService.getById(id),
        enabled: !!id,
    })
}

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

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

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

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

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

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