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

export function useBanners() {
    return useQuery({
        queryKey: ["banners"],
        queryFn: bannerService.getAll,
    })
}

export function useBanner(id: string) {
    return useQuery({
        queryKey: ["banner", id],
        queryFn: () => bannerService.getById(id),
        enabled: !!id,
    })
}

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

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

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

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

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

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