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

export function useSiteInfos() {
    return useQuery({
        queryKey: ["siteInfos"],
        queryFn: siteInfoService.getAll,
    })
}

export function useSiteInfo(id: string) {
    return useQuery({
        queryKey: ["siteInfo", id],
        queryFn: () => siteInfoService.getById(id),
        enabled: !!id,
    })
}

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

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

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

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

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

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