import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { signalPipelineService } from '../services/signalPipelineService'
import type { GateType } from '../domain/signalPipeline'
import { useToastStore } from '../stores/toastStore'

const STALE_PIPELINE = 15_000

export function useSignalPipelineState(signalId: string | null) {
  return useQuery({
    queryKey: ['signal-pipeline', signalId],
    queryFn: () => signalPipelineService.getPipelineState(signalId!),
    enabled: signalId !== null,
    staleTime: STALE_PIPELINE,
    select: (res) => res.data ?? null,
  })
}

export function useSignalAuditTrail(signalId: string | null) {
  return useQuery({
    queryKey: ['signal-audit-trail', signalId],
    queryFn: () => signalPipelineService.getAuditTrail(signalId!),
    enabled: signalId !== null,
    staleTime: STALE_PIPELINE,
    select: (res) => res.data ?? [],
  })
}

export function useEvaluateGate() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({ signalId, gateType }: { signalId: string; gateType: GateType }) =>
      signalPipelineService.evaluateGate(signalId, gateType),
    onSuccess: (_data, { signalId }) => {
      queryClient.invalidateQueries({ queryKey: ['signal-pipeline', signalId] })
    },
    onError: () => {
      useToastStore.getState().showToast('Gate-Evaluierung fehlgeschlagen.', 'error')
    },
  })
}

export function usePublishToFutureAvailability() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (signalId: string) => signalPipelineService.publishToFutureAvailability(signalId),
    onSuccess: (_data, signalId) => {
      queryClient.invalidateQueries({ queryKey: ['signal-pipeline', signalId] })
      queryClient.invalidateQueries({ queryKey: ['signal-audit-trail', signalId] })
      queryClient.invalidateQueries({ queryKey: ['market-signals'] })
    },
    onError: () => {
      useToastStore.getState().showToast('Veröffentlichung fehlgeschlagen. Bitte versuchen Sie es erneut.', 'error')
    },
  })
}
