import { describe, it, expect } from 'vitest'
import {
  buildPatientReport,
  buildSbar,
  buildWardSummary,
  extractLatestVitals,
  formatAlertsSummary,
  formatVitalsSummary,
} from '@/composables/handoffReport'

const wardPatient = {
  encounterId: 'enc-1',
  firstName: 'Jane',
  lastName: 'Doe',
  mrn: 'MRN001',
  roomBed: 'ICU-3',
  department: 'ICU',
  attendingPhysician: 'Dr Smith',
  news2Score: 8,
  sofaScore: 6,
  sofaDelta: 2,
  gcsScore: 14,
  qsofaScore: 2,
  openAlertCount: 1,
}

const enrichment = {
  encounter: {
    admissionReason: 'Sepsis workup',
    patient: { allergies: 'Penicillin' },
  },
  openAlerts: [{ alertType: 'News2Emergency' }],
  pendingOrders: [{ description: 'Blood cultures', status: 'Pending' }],
  vitals: extractLatestVitals([
    { observationCode: 'HEART_RATE', value: 110, unit: 'bpm', recordedAt: '2026-06-23T10:00:00Z' },
    { observationCode: 'SPO2', value: 94, unit: '%', recordedAt: '2026-06-23T10:00:00Z' },
  ]),
  bundle: null,
}

describe('handoffReport', () => {
  it('buildsWardSummary', () => {
    const summary = buildWardSummary(
      [
        wardPatient,
        { news2Score: 3, openAlertCount: 0, sepsisActive: true },
      ],
      'ICU',
    )
    expect(summary).toMatchObject({
      department: 'ICU',
      patientCount: 2,
      criticalCount: 1,
      alertCount: 1,
      activeBundles: 1,
    })
  })

  it('formatsLatestVitals', () => {
    expect(formatVitalsSummary(enrichment.vitals)).toContain('HR 110 bpm')
    expect(formatVitalsSummary(enrichment.vitals)).toContain('SpO₂ 94%')
  })

  it('formatsAlertSummary', () => {
    expect(formatAlertsSummary(enrichment.openAlerts)).toContain('NEWS2 Emergency')
  })

  it('buildsPatientReportWithSbar', () => {
    const report = buildPatientReport(wardPatient, enrichment)
    expect(report.name).toBe('Jane Doe')
    expect(report.pendingOrders).toContain('Blood cultures')
    expect(report.sbar.situation).toBe('Sepsis workup')
    expect(report.sbar.background).toContain('Penicillin')
    expect(report.sbar.assessment).toContain('NEWS2 8')
    expect(report.sbar.recommendation).toContain('Blood cultures')
  })

  it('includesBundleInRecommendation', () => {
    const sbar = buildSbar(wardPatient, enrichment.encounter, {
      ...enrichment,
      pendingOrders: [],
      bundle: {
        complianceStatus: 'IN_PROGRESS',
        elements: [
          { elementType: 'BloodCultures', status: 'Pending' },
          { elementType: 'SerumLactate', status: 'Completed' },
        ],
      },
    })
    expect(sbar.recommendation).toContain('Sepsis bundle')
    expect(sbar.recommendation).toContain('Blood cultures')
  })
})
