import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { fetchSites, updateSite, deleteSite, reorderSites, adaptSite, fetchSiteSelectors } from '@/lib/api/sites'
import type { TargetSite } from '@/lib/types'

const KEY = ['sites']

export const useSites = () => useQuery({ queryKey: KEY, queryFn: fetchSites })
export const useSiteSelectors = (id: number) => useQuery({ queryKey: ['selectors', id], queryFn: () => fetchSiteSelectors(id), staleTime: 30_000 })

export const useUpdateSite = () => {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: ({ id, data }: { id: number; data: Partial<TargetSite> }) => updateSite(id, data),
    onSuccess: () => qc.invalidateQueries({ queryKey: KEY })
  })
}

export const useDeleteSite = () => {
  const qc = useQueryClient()
  return useMutation({ mutationFn: deleteSite, onSuccess: () => qc.invalidateQueries({ queryKey: KEY }) })
}

export const useReorderSites = () => {
  const qc = useQueryClient()
  return useMutation({ mutationFn: reorderSites, onSuccess: () => qc.invalidateQueries({ queryKey: KEY }) })
}

export const useAdaptSite = () => {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: adaptSite,
    onSuccess: (_, id) => qc.invalidateQueries({ queryKey: ['selectors', id] })
  })
}
