import { describe, it, expect, beforeEach, vi } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import { useAuthStore } from '@/stores/auth'
import { useSimulationStore } from '@/stores/simulation'

const { fetchSimulationConfig } = vi.hoisted(() => ({
  fetchSimulationConfig: vi.fn(),
}))

vi.mock('@/api/simulation', () => ({
  fetchSimulationConfig,
  fetchScenarios: vi.fn(),
  fetchRuns: vi.fn(),
  startRun: vi.fn(),
  stopRun: vi.fn(),
  fetchRun: vi.fn(),
}))

describe('simulation router guard', () => {
  beforeEach(async () => {
    vi.clearAllMocks()
    setActivePinia(createPinia())

    const auth = useAuthStore()
    auth.token = 'test-token'
    auth.user = {
      userId: 'u1',
      username: 'nurse',
      displayName: 'Test Nurse',
      role: 'NURSE',
    }

    fetchSimulationConfig.mockResolvedValue({ enabled: false })

    const { default: router } = await import('@/router')
    // Reset to a known route; ignore failures from first load
    await router.push('/ward').catch(() => {})
    await router.isReady()
  })

  it('redirectsDirectSimulationNavigationWhenDisabled', async () => {
    const sim = useSimulationStore()
    sim.enabled = false

    const { default: router } = await import('@/router')
    await router.push('/simulation')

    expect(router.currentRoute.value.path).toBe('/ward')
    expect(fetchSimulationConfig).toHaveBeenCalled()
  })

  it('allowsSimulationWhenEnabled', async () => {
    const sim = useSimulationStore()
    sim.enabled = true

    const { default: router } = await import('@/router')
    await router.push('/simulation')

    expect(router.currentRoute.value.path).toBe('/simulation')
  })
})
