import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { fetchActiveEncounters } from '@/api/encounters'
import { fetchCurrentNews2 } from '@/api/clinical'

export const useWardStore = defineStore('ward', () => {
  const encounters = ref([])
  const loading = ref(false)
  const error = ref(null)
  const department = ref(null)

  const sortedByRisk = computed(() =>
    [...encounters.value].sort((a, b) => (b.news2Score ?? 0) - (a.news2Score ?? 0))
  )

  const criticalCount = computed(() =>
    encounters.value.filter(e => (e.news2Score ?? 0) >= 7).length
  )

  async function loadEncounters() {
    loading.value = true
    error.value = null
    try {
      const data = await fetchActiveEncounters(department.value)
      encounters.value = data.items
    } catch (e) {
      error.value = e.message
    } finally {
      loading.value = false
    }
  }

  function setDepartment(dept) {
    department.value = dept
    loadEncounters()
  }

  return { encounters, loading, error, department, sortedByRisk, criticalCount, loadEncounters, setDepartment }
})