import { watch } from 'vue'
import { useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

import { useUiStore } from '@/stores/uiStore'

/**
 * Composable that validates trace/node existence and handles redirects.
 * Should be used in TraceView.vue - the component responsible for displaying traces.
 */
export function useTraceValidation() {
  const router = useRouter()
  const uiStore = useUiStore()

  // watch for trace fetch errors (404)
  watch(
    () => uiStore.isTraceError,
    (hasError) => {
      if (hasError && uiStore.selectedTraceId) {
        const traceId = uiStore.selectedTraceId

        // clear selection first, then redirect
        uiStore.selectTrace(undefined)

        toast.error('Trace not found', {
          description: `The trace "${traceId}" does not exist.`,
        })

        router.push({ name: 'traceList' })
      }
    },
  )

  // watch for node not found (node ID set but node doesn't exist in loaded trace)
  watch(
    () => ({
      trace: uiStore.selectedTrace,
      node: uiStore.selectedNode,
      nodeId: uiStore.selectedNodeId,
    }),
    ({ trace, node, nodeId }) => {
      // only check when: trace is loaded, node ID is set, but node wasn't found
      if (trace?.parentNode && nodeId && !node) {
        const invalidNodeId = nodeId

        // clear node selection, keep trace
        uiStore.selectedNodeId = undefined

        toast.error('Node not found', {
          description: `The node "${invalidNodeId}" does not exist.`,
        })

        router.push({ name: 'trace', params: { traceId: uiStore.selectedTraceId } })
      }
    },
  )
}
