import { describe, it, expect, vi, beforeEach } from 'vitest'
import { setActivePinia, createPinia } from 'pinia'
import { useAlertQualityStore } from '@/stores/alertQuality'

const {
  submitAlertFeedback,
  fetchQualityMetricsSummary,
  fetchQualityMetrics,
  fetchQualityFeedback,
} = vi.hoisted(() => ({
  submitAlertFeedback: vi.fn().mockResolvedValue({ id: 'fb-1', createdAt: '2026-06-23T00:00:00Z' }),
  fetchQualityMetricsSummary: vi.fn().mockResolvedValue({
    totalAlerts: 10, totalFeedback: 4,
    acknowledgementRate: 0.8, usefulRate: 0.75,
    falsePositiveRate: 0.1, wouldActRate: 0.6,
    avgSecondsToAcknowledge: 300, avgSecondsToResolution: 1200,
  }),
  fetchQualityMetrics: vi.fn().mockResolvedValue({
    items: [{ alertType: 'News2Warning', usefulRate: 0.75, falsePositiveRate: 0.1, acknowledgementRate: 0.8, totalAlerts: 5 }],
  }),
  fetchQualityFeedback: vi.fn().mockResolvedValue({
    items: [
      {
        id: '1',
        alertId: 'a1',
        alertType: 'NEWS2_WARNING',
        feedbackType: 'USEFUL',
        comment: null,
        createdAt: '2026-06-23T00:00:00Z',
        scenarioId: 'uti-sepsis-elderly-01',
        sessionId: 'session-b-alert-quality',
      },
      {
        id: '2',
        alertId: 'a2',
        alertType: 'NEWS2_WARNING',
        feedbackType: 'FALSE_POSITIVE',
        comment: null,
        createdAt: '2026-06-23T01:00:00Z',
        scenarioId: 'medication-false-alarm-01',
        sessionId: 'session-b-alert-quality',
      },
      {
        id: '3',
        alertId: 'a3',
        alertType: 'NEWS2_WARNING',
        feedbackType: 'FALSE_POSITIVE',
        comment: null,
        createdAt: '2026-06-23T02:00:00Z',
        scenarioId: 'medication-false-alarm-01',
        sessionId: null,
      },
    ],
  }),
}))

vi.mock('@/api/alertQuality', () => ({
  submitAlertFeedback,
  fetchQualityMetricsSummary,
  fetchQualityMetrics,
  fetchQualityFeedback,
  FEEDBACK_TYPE_MAP: { useful: 'Useful' },
}))

describe('alertQuality store', () => {
  beforeEach(() => {
    setActivePinia(createPinia())
    vi.clearAllMocks()
  })

  it('loads dashboard summary and snapshots', async () => {
    const store = useAlertQualityStore()
    await store.loadDashboard()
    expect(store.summaryStats.totalAlerts).toBe(10)
    expect(store.summaryStats.usefulRate).toBe(75)
    expect(store.snapshots).toHaveLength(1)
  })

  it('caches submitted feedback per alert', async () => {
    const store = useAlertQualityStore()
    await store.submitFeedback('alert-1', 'useful', 'test note')
    expect(store.getFeedback('alert-1').rating).toBe('useful')
  })

  it('groupsFeedbackByScenario', async () => {
    const store = useAlertQualityStore()
    await store.loadDashboard()

    expect(store.scenarioOptions).toEqual([
      'medication-false-alarm-01',
      'uti-sepsis-elderly-01',
    ])

    const med = store.byScenario.find(s => s.scenarioId === 'medication-false-alarm-01')
    expect(med.totalFeedback).toBe(2)
    expect(med.falsePositiveRate).toBe(1)
    expect(med.usefulRate).toBe(0)
  })

  it('passesScenarioFilterToFeedbackApi', async () => {
    const store = useAlertQualityStore()
    store.setScenarioFilter('uti-sepsis-elderly-01')
    await store.loadDashboard()

    expect(fetchQualityFeedback).toHaveBeenCalledWith(
      expect.objectContaining({ scenarioId: 'uti-sepsis-elderly-01' }),
    )
  })

  it('csvIncludesScenarioColumns', async () => {
    const store = useAlertQualityStore()
    await store.loadDashboard()
    const csv = store.buildCsv()
    expect(csv.split('\n')[0]).toContain('scenarioId')
    expect(csv.split('\n')[0]).toContain('sessionId')
    expect(csv).toContain('uti-sepsis-elderly-01')
    expect(csv).toContain('session-b-alert-quality')
  })
})
