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

import { tracesService } from '@/api/services/tracesService'
import { LOCAL_TRACE_STORAGE_KEY } from '@/utils/config'

/**
 * 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
 *
 * @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(() => {
      const traceId = unref(id)
      return !!traceId && !traceId.startsWith(LOCAL_TRACE_STORAGE_KEY)
    }),
    retry: false, // Don't retry on 404
  })
}

/**
 * useProcessTrace - Mutation for processing pasted trace JSON via backend.
 * Does not store in repository - returns processed trace for client-side storage.
 *
 * @returns {Object} Mutation object with mutateAsync, isPending, etc.
 */
export function useProcessTrace() {
  return useMutation({
    mutationFn: tracesService.process,
    onError: (error) => {
      console.error('Failed to process trace:', error)
    },
  })
}
