import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'

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

vi.mock('@/api', () => ({
  default: {
    get: apiGetMock,
    post: vi.fn(),
    interceptors: {
      request: { use: vi.fn() },
      response: { use: vi.fn() },
    },
  },
}))

describe('auth router guard', () => {
  beforeEach(() => {
    vi.resetModules()
    localStorage.clear()
    apiGetMock.mockReset()
    window.history.replaceState({}, '', '/')
    setActivePinia(createPinia())
  })

  it('redirects to /login when a stored token fails validation during startup', async () => {
    localStorage.setItem('access_token', 'stale-token')
    apiGetMock.mockRejectedValueOnce({ response: { status: 401 } })

    const { default: router } = await import('./index')

    await router.push('/chat')

    expect(router.currentRoute.value.fullPath).toBe('/login')
  })
})
