import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

import { useTraces } from '@/composables/useTraces'
import type { Trace } from '@/types/trace'

/**
 * Pure data store for trace data.
 * Contains loaded traces and local (pasted) trace.
 * Selection and filtering logic is in uiStore.
 */
export const useTracesStore = defineStore('traces', () => {
  // local trace pasted by user
  const localTrace = ref<Trace | undefined>(undefined)

  // remote traces from API via TanStack Query
  const { data: traces, isLoading: isLoadingList } = useTraces()

  /**
   * Whether any traces were loaded from the API (excludes local traces).
   * Used to determine empty state message and filter visibility.
   */
  const hasApiTraces = computed(() => (traces.value?.data.length || 0) > 0)

  // actions
  function setLocalTrace(trace: Trace | undefined) {
    if (!trace) return
    localTrace.value = trace
  }

  function clearLocalTrace() {
    localTrace.value = undefined
  }

  return {
    localTrace,
    traces,
    hasApiTraces,
    isLoadingList,
    setLocalTrace,
    clearLocalTrace,
  }
})
