import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { setActivePinia, createPinia } from 'pinia'
import type { User } from '@/types'

const makeUser = (overrides: Partial<User> = {}): User => ({
  id: 1,
  email: 'test@example.com',
  roles: ['ROLE_USER'],
  theme: null,
  designVersion: 'v1',
  timezone: 'America/Chicago',
  ...overrides,
})

describe('auth store', () => {
  beforeEach(() => {
    vi.unstubAllGlobals()
    vi.restoreAllMocks()
    setActivePinia(createPinia())
  })

  afterEach(() => {
    // unstubAllGlobals is handled in beforeEach and globally in setup.ts
  })

  it('isAuthenticated is false when __PF_USER__ is not set', async () => {
    // No __PF_USER__ on window — should be null
    vi.stubGlobal('__PF_USER__', undefined)
    const { useAuthStore } = await import('@/stores/auth')
    const store = useAuthStore()
    expect(store.isAuthenticated).toBe(false)
    expect(store.user).toBeNull()
  })

  it('isAuthenticated is true when user is set via setUser', async () => {
    vi.stubGlobal('__PF_USER__', undefined)
    const { useAuthStore } = await import('@/stores/auth')
    const store = useAuthStore()

    store.setUser(makeUser())
    expect(store.isAuthenticated).toBe(true)
    expect(store.user?.email).toBe('test@example.com')
  })

  it('setUser(null) clears user and isAuthenticated becomes false', async () => {
    vi.stubGlobal('__PF_USER__', undefined)
    const { useAuthStore } = await import('@/stores/auth')
    const store = useAuthStore()

    store.setUser(makeUser())
    expect(store.isAuthenticated).toBe(true)

    store.setUser(null)
    expect(store.isAuthenticated).toBe(false)
    expect(store.user).toBeNull()
  })

  it('bootstraps user from window.__PF_USER__ when present', async () => {
    const user = makeUser({ id: 99, email: 'bootstrapped@example.com' })
    // Stub window.__PF_USER__ before the store module is evaluated
    vi.stubGlobal('__PF_USER__', user)

    // Dynamically re-import so the store sees the stub
    vi.resetModules()
    const { useAuthStore } = await import('@/stores/auth')
    setActivePinia(createPinia())
    const store = useAuthStore()

    expect(store.isAuthenticated).toBe(true)
    expect(store.user?.id).toBe(99)
  })
})
