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 { getLocalTraceItemName, getRawTraceFromLS, getTraceFromLS } from '@/utils/localStorage'
import { useTracesStore } from '@/stores/tracesStore'
import { useUiStore } from '@/stores/uiStore'

/**
 * Composable handling the initial loading of traces from LocalStorage or URL parameters.
 * Also triggers reload from backend before fetching the traces list.
 */
export function useAppInitialization() {
  const navigation = useNavigation()
  const tracesStore = useTracesStore()
  const uiStore = useUiStore()

  onMounted(async () => {
    // loading local trace
    const itemName = getLocalTraceItemName(window.location.href)
    tracesStore.setLocalTrace(getTraceFromLS(itemName))

    // 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)

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

        tracesStore.setLocalTrace(trace)
        if (trace?.id) {
          localStorage.setItem(getLocalTraceItemName(window.location.href), JSON.stringify(trace))
          uiStore.selectTrace(trace.id)
          navigation.goToTrace(trace.id)
        }
      } catch (error) {
        console.error('Failed to load explore trace:', error)
      }
    }
  })
}
