import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
  submitAlertFeedback,
  fetchQualityMetricsSummary,
  fetchQualityMetrics,
} from '@/api/alertQuality'

export const useAlertQualityStore = defineStore('alertQuality', () => {
  const summary = ref(null)
  const snapshots = ref([])
  const periodDays = ref(7)
  const selectedAlertType = ref(null)
  const loading = ref(false)
  const error = ref(null)

  // Per-alert feedback cache: alertId → { rating, comment, submittedAt }
  const feedbackByAlert = ref({})

  const summaryStats = computed(() => {
    const s = summary.value
    if (!s) {
      return {
        totalAlerts: 0,
        totalFeedback: 0,
        acknowledgementRate: 0,
        usefulRate: 0,
        falsePositiveRate: 0,
        wouldActRate: 0,
        avgAckMinutes: 0,
        avgResolveMinutes: 0,
      }
    }
    return {
      totalAlerts: s.totalAlerts,
      totalFeedback: s.totalFeedback,
      acknowledgementRate: Math.round(s.acknowledgementRate * 100),
      usefulRate: Math.round(s.usefulRate * 100),
      falsePositiveRate: Math.round(s.falsePositiveRate * 100),
      wouldActRate: Math.round(s.wouldActRate * 100),
      avgAckMinutes: Math.round(s.avgSecondsToAcknowledge / 60),
      avgResolveMinutes: Math.round(s.avgSecondsToResolution / 60),
    }
  })

  const byAlertType = computed(() => {
    const map = {}
    for (const snap of snapshots.value) {
      if (!map[snap.alertType]) map[snap.alertType] = []
      map[snap.alertType].push(snap)
    }
    return map
  })

  function periodRange() {
    const to = new Date().toISOString()
    const from = new Date(Date.now() - periodDays.value * 86_400_000).toISOString()
    return { from, to }
  }

  async function loadDashboard() {
    loading.value = true
    error.value = null
    try {
      const { from, to } = periodRange()
      const [sum, list] = await Promise.all([
        fetchQualityMetricsSummary(from, to),
        fetchQualityMetrics({
          alertType: selectedAlertType.value,
          from,
          to,
        }),
      ])
      summary.value = sum
      snapshots.value = list.items ?? []
    } catch (e) {
      error.value = e.message
    } finally {
      loading.value = false
    }
  }

  async function submitFeedback(alertId, rating, comment = '') {
    const result = await submitAlertFeedback(alertId, rating, comment)
    feedbackByAlert.value[alertId] = {
      rating,
      comment,
      submittedAt: result.createdAt,
      feedbackType: result.feedbackType,
    }
    return result
  }

  function getFeedback(alertId) {
    return feedbackByAlert.value[alertId] ?? null
  }

  function setPeriodDays(days) {
    periodDays.value = days
  }

  function setAlertTypeFilter(type) {
    selectedAlertType.value = type
  }

  return {
    summary,
    snapshots,
    periodDays,
    selectedAlertType,
    loading,
    error,
    summaryStats,
    byAlertType,
    loadDashboard,
    submitFeedback,
    getFeedback,
    setPeriodDays,
    setAlertTypeFilter,
  }
})