import { afterEach, describe, expect, it, vi } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import { useAuthStore } from '../src/stores/auth'
import { apiFetch } from '../src/services/api'

afterEach(() => {
  vi.unstubAllGlobals()
})

describe('auth store', () => {
  it('shares the initial refresh across overlapping router guards', async () => {
    setActivePinia(createPinia())
    const store = useAuthStore()

    let resolveRefresh!: (response: Response) => void
    const fetchMock = vi.fn(() => new Promise<Response>(resolve => {
      resolveRefresh = resolve
    }))
    vi.stubGlobal('fetch', fetchMock)

    const firstGuard = store.initialize()
    const secondGuard = store.initialize()

    expect(fetchMock).toHaveBeenCalledTimes(1)

    resolveRefresh(new Response(JSON.stringify({
      accessToken: 'test-access-token',
      expiresAt: '2026-07-28T12:00:00.000Z',
      user: {
        id: 'bao',
        email: 'bao@nexus.local',
        displayName: 'Bao',
        role: 'owner',
      },
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' },
    }))

    await expect(Promise.all([firstGuard, secondGuard])).resolves.toEqual([true, true])
    expect(store.isAuthenticated).toBe(true)
    expect(store.user?.displayName).toBe('Bao')
  })

  it('uses the JWT without emitting a browser-controlled agent identity header', async () => {
    setActivePinia(createPinia())
    const store = useAuthStore()
    store.initialized = true
    store.applySession({
      accessToken: 'signed-jwt',
      expiresAt: '2026-07-28T12:00:00.000Z',
      user: {
        id: 'iris-user',
        email: 'iris@nexus.local',
        displayName: 'Iris',
        role: 'owner',
      },
    })

    const fetchMock = vi.fn(() => Promise.resolve(new Response(null, { status: 204 })))
    vi.stubGlobal('fetch', fetchMock)

    await apiFetch('/api/v1/tasks/board')

    const requestInit = fetchMock.mock.calls[0]?.[1] as RequestInit
    const headers = new Headers(requestInit.headers)
    expect(headers.get('Authorization')).toBe('Bearer signed-jwt')
    expect(headers.has('X-Agent-Id')).toBe(false)
  })
})
