import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { fetchSepsisBundles } from '@/api/sepsis'
import { sortBundlesByUrgency, summarizeBundles } from '@/composables/sepsisFormat'

export const useSepsisStore = defineStore('sepsis', () => {
  const bundles = ref([])
  const loading = ref(false)
  const error = ref(null)
  const now = ref(Date.now())

  const sortedBundles = computed(() => sortBundlesByUrgency(bundles.value, now.value))

  const summary = computed(() => summarizeBundles(bundles.value, now.value))

  async function loadBundles(status = 'IN_PROGRESS') {
    loading.value = true
    error.value = null
    try {
      const data = await fetchSepsisBundles({ status, pageSize: 100 })
      bundles.value = data.items ?? []
      now.value = Date.now()
    } catch (e) {
      error.value = e.message
    } finally {
      loading.value = false
    }
  }

  function tick() {
    now.value = Date.now()
  }

  return { bundles, loading, error, sortedBundles, summary, now, loadBundles, tick }
})
