import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { aiMonitoringService } from '../services/aiMonitoringService'
import type { AIMonitoringFilters } from '../provider/IAIMonitoringProvider'
import type { ReviewStatus } from '../domain/enums'
import { useToastStore } from '../stores/toastStore'

const QK = 'aiOutputs'
const STALE = 30_000

export function useAIOutputs(filters?: AIMonitoringFilters) {
  return useQuery({
    queryKey: [QK, filters ?? {}],
    queryFn: () => aiMonitoringService.getOutputs(filters),
    staleTime: STALE,
    select: (res) => res.data ?? [],
  })
}

export function useAIOutput(id: string | null) {
  return useQuery({
    queryKey: [QK, 'detail', id],
    queryFn: () => aiMonitoringService.getOutput(id!),
    staleTime: STALE,
    enabled: !!id,
    select: (res) => res.data ?? null,
  })
}

export function useUpdateAIOutputReviewStatus() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: ({ id, status }: { id: string; status: ReviewStatus }) =>
      aiMonitoringService.updateReviewStatus(id, status),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: [QK] })
    },
    onError: () => {
      useToastStore.getState().showToast('Status konnte nicht aktualisiert werden.', 'error')
    },
  })
}
