import { onMounted } from 'vue'

import { useNavigation } from './useNavigation'
import { tracesService } from '@/api/services/tracesService'
import { URL_EXPLORE_TRACE_PARAM_KEY, EXPLORE_TRACE_STORAGE_KEY } from '@/utils/config'
import { getRawTraceFromLS } from '@/utils/localStorage'
import { useUiStore } from '@/stores/uiStore'

/**
 * Composable handling initial URL-based trace import.
 * Supports one-shot `readTraceFromLS` handoff from localStorage.
 */
export function useAppInitialization() {
  const navigation = useNavigation()
  const uiStore = useUiStore()

  onMounted(async () => {
    // loading explore trace
    const urlObj = new URL(window.location.href)
    if (urlObj.searchParams.get(URL_EXPLORE_TRACE_PARAM_KEY) == 'true') {
      const exploreTraceLS = getRawTraceFromLS(EXPLORE_TRACE_STORAGE_KEY)

      if (!exploreTraceLS) return

      try {
        const result = await tracesService.process({
          traceJson: exploreTraceLS,
        })
        const trace = result.data

        if (trace?.id) {
          localStorage.removeItem(EXPLORE_TRACE_STORAGE_KEY)
          uiStore.selectTrace(trace.id)
          navigation.goToTrace(trace.id)
        }
      } catch (error) {
        console.error('Failed to load explore trace:', error)
      }
    }
  })
}
