import { type MaybeRef, unref, computed } from 'vue'
import { useQuery, useMutation, useQueryClient } from '@tanstack/vue-query'

import { tracesService } from '@/api/services/tracesService'

/**
 * useReloadTraces - Mutation for reloading traces from backend dataset.
 * After reload completes, triggers traces query to fetch the list.
 *
 * @returns {Object} Mutation object with mutate, mutateAsync, isPending, etc.
 */
export function useReloadTraces() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: tracesService.reload,
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ['traces'] })
    },
    onError: (error) => {
      console.error('Failed to reload traces:', error)
      queryClient.refetchQueries({ queryKey: ['traces'] })
    },
  })
}

/**
 * useTraces - Returns a query for all traces.
 *
 * @returns {Object} An object containing the queries
 */
export function useTraces() {
  return useQuery({
    queryKey: ['traces'],
    queryFn: tracesService.listAll,
  })
}

/**
 * useTrace - Returns a query for a specific trace
 * Auto refresh is disabled to avoid repeated 404 responses when a trace
 * no longer exists (for example with no_storage mode).
 *
 * @param {string | null | undefined} id - The ID of the trace
 * @returns {Object} An object containing the query
 */
export function useTrace(id: MaybeRef<string | null | undefined>) {
  return useQuery({
    queryKey: ['traces', id],
    queryFn: () => {
      const traceId = unref(id)
      if (!traceId) throw new Error('Trace ID is missing')
      return tracesService.getOne(traceId)
    },
    enabled: computed(() => !!unref(id)),
    staleTime: Infinity,
    refetchOnWindowFocus: false,
    refetchOnReconnect: false,
    refetchOnMount: false,
    retry: false, // Don't retry on 404
  })
}

/**
 * useProcessTrace - Mutation for processing pasted trace JSON via backend.
 * Persists pasted trace on backend and returns processed trace details.
 *
 * @returns {Object} Mutation object with mutateAsync, isPending, etc.
 */
export function useProcessTrace() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: tracesService.process,
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ['traces'] })
    },
    onError: (error) => {
      console.error('Failed to process trace:', error)
    },
  })
}

/**
 * useDeletePastedTrace - Mutation to delete one pasted trace.
 */
export function useDeletePastedTrace() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (id: string) => tracesService.deletePasted(id),
    onSettled: () => {
      queryClient.refetchQueries({ queryKey: ['traces'] })
    },
  })
}

/**
 * useDeleteAllPastedTraces - Mutation to delete all pasted traces.
 */
export function useDeleteAllPastedTraces() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: tracesService.deleteAllPasted,
    onSettled: () => {
      queryClient.refetchQueries({ queryKey: ['traces'] })
    },
  })
}
