import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { fetchAllActiveEncounters } from '@/api/encounters'
import { fetchAlertSummary } from '@/api/analytics'
import { aggregateByDepartment, summarizeDepartments } from '@/composables/departmentFormat'

export const useDepartmentsStore = defineStore('departments', () => {
  const encounters = ref([])
  const alertSummary = ref([])
  const loading = ref(false)
  const error = ref(null)

  const departments = computed(() =>
    aggregateByDepartment(encounters.value, alertSummary.value),
  )

  const totals = computed(() => summarizeDepartments(departments.value))

  async function load() {
    loading.value = true
    error.value = null
    try {
      const [encounterItems, alertData] = await Promise.all([
        fetchAllActiveEncounters(),
        fetchAlertSummary(),
      ])
      encounters.value = encounterItems
      alertSummary.value = alertData.summary ?? []
    } catch (e) {
      error.value = e.message
    } finally {
      loading.value = false
    }
  }

  return { encounters, alertSummary, departments, totals, loading, error, load }
})
