import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { futureSignalService } from '../services/futureSignalService'
import type { ReviewStatus } from '../domain/enums'
import { STALE_SIGNALS } from '../lib/constants'

export function useFutureSignals() {
  return useQuery({
    queryKey: ['futureSignals'],
    queryFn: () => futureSignalService.getAll(),
    staleTime: STALE_SIGNALS,
    select: (res) => res.data ?? [],
  })
}

export function useFutureSignal(id: string) {
  return useQuery({
    queryKey: ['futureSignal', id],
    queryFn: () => futureSignalService.getById(id),
    staleTime: STALE_SIGNALS,
    enabled: !!id,
    select: (res) => res.data ?? null,
  })
}

export function useFutureSignalsByProperty(propertyId: string) {
  return useQuery({
    queryKey: ['futureSignals', 'property', propertyId],
    queryFn: () => futureSignalService.getByProperty(propertyId),
    staleTime: STALE_SIGNALS,
    enabled: Boolean(propertyId),
    select: (res) => res.data ?? [],
  })
}

export function useVerifySignal() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (signalId: string) => futureSignalService.verify(signalId, 'admin@ideal-sharing.ch'),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['futureSignals'] })
    },
  })
}

export function useUpdateSignalReviewStatus() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({ id, status }: { id: string; status: ReviewStatus }) =>
      futureSignalService.updateReviewStatus(id, status),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['futureSignals'] })
      queryClient.invalidateQueries({ queryKey: ['futureSignal'] })
    },
  })
}
