import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import * as alertsApi from '@/api/alerts'

export const useAlertStore = defineStore('alerts', () => {
  const alerts = ref([])
  const loading = ref(false)
  const statusFilter = ref(null)

  const openAlerts = computed(() => alerts.value.filter(a => a.status === 'Open'))
  const criticalAlerts = computed(() => alerts.value.filter(a => a.severity === 'Critical'))

  async function loadAlerts(encounterId, status) {
    loading.value = true
    try {
      const filter = status ?? statusFilter.value
      const data = await alertsApi.fetchAlerts(encounterId, filter)
      alerts.value = data.items
    } catch (e) {
      console.error('Failed to load alerts', e)
    } finally {
      loading.value = false
    }
  }

  async function loadGlobalAlerts(status = 'OPEN') {
    loading.value = true
    try {
      const data = await alertsApi.fetchAllAlerts(status)
      alerts.value = data.items
    } catch (e) {
      console.error('Failed to load alerts', e)
    } finally {
      loading.value = false
    }
  }

  async function acknowledge(alertId, note) {
    await alertsApi.acknowledgeAlert(alertId, note)
    const alert = alerts.value.find(a => a.id === alertId)
    if (alert) alert.status = 'Acknowledged'
  }

  async function resolve(alertId) {
    await alertsApi.resolveAlert(alertId)
    const alert = alerts.value.find(a => a.id === alertId)
    if (alert) alert.status = 'Resolved'
  }

  return { alerts, loading, statusFilter, openAlerts, criticalAlerts, loadAlerts, loadGlobalAlerts, acknowledge, resolve }
})