import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { getToken, setToken, removeToken } from '@/utils/auth'

describe('Auth Utils', () => {
  const mockToken = 'mock-jwt-token-12345'

  beforeEach(() => {
    // Clear cookies before each test
    document.cookie.split(';').forEach((c) => {
      document.cookie = c.replace(/^ +/, '').replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/')
    })
  })

  afterEach(() => {
    // Clean up after each test
    document.cookie.split(';').forEach((c) => {
      document.cookie = c.replace(/^ +/, '').replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/')
    })
  })

  describe('Token Management (Cookie-based)', () => {
    it('should set and get token', () => {
      setToken(mockToken)
      expect(getToken()).toBe(mockToken)
    })

    it('should set token with custom expiresIn', () => {
      const customExpiry = 7200 // 2 hours
      setToken(mockToken, customExpiry)
      expect(getToken()).toBe(mockToken)
    })

    it('should return null when token is not set', () => {
      expect(getToken()).toBeNull()
    })

    it('should remove token', () => {
      setToken(mockToken)
      expect(getToken()).toBe(mockToken)

      removeToken()
      expect(getToken()).toBeNull()
    })

    it('should overwrite existing token', () => {
      setToken(mockToken)
      const newToken = 'new-token-54321'
      setToken(newToken)
      expect(getToken()).toBe(newToken)
    })

    it('should handle special characters in token', () => {
      const specialToken = 'token+with/special=chars'
      setToken(specialToken)
      expect(getToken()).toBe(specialToken)
    })
  })
})
