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

export function useExperiences(resumeId?: string) {
    return useQuery({
        queryKey: ["experiences", resumeId],
        queryFn: () => experienceService.getAll(resumeId),
    })
}

export function useExperience(id: string) {
    return useQuery({
        queryKey: ["experience", id],
        queryFn: () => experienceService.getById(id),
        enabled: !!id,
    })
}

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

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

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

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

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

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