import { beforeEach, describe, expect, it, vi } from 'vitest';
import { persistAccessToken, readStoredAccessToken } from './auth-storage';

class MemoryStorage {
  private values = new Map<string, string>();
  getItem(key: string) { return this.values.get(key) ?? null; }
  setItem(key: string, value: string) { this.values.set(key, value); }
  removeItem(key: string) { this.values.delete(key); }
}

describe('auth storage', () => {
  beforeEach(() => {
    vi.stubGlobal('window', { localStorage: new MemoryStorage(), sessionStorage: new MemoryStorage() });
  });

  it('persists only explicit local or externally supplied bearer tokens', () => {
    persistAccessToken('local-token');
    expect(readStoredAccessToken()).toBe('local-token');
    expect(window.localStorage.getItem('easyai_ai_gateway_access_token')).toBe('local-token');
    expect(window.sessionStorage.getItem('easyai_ai_gateway_oidc_access_token')).toBeNull();
  });

  it('removes and never reads a legacy OIDC browser token', () => {
    window.sessionStorage.setItem('easyai_ai_gateway_oidc_access_token', 'legacy-oidc-token');
    expect(readStoredAccessToken()).toBe('');
    expect(window.sessionStorage.getItem('easyai_ai_gateway_oidc_access_token')).toBeNull();
  });

  it('clears both token stores on logout', () => {
	window.sessionStorage.setItem('easyai_ai_gateway_oidc_access_token', 'legacy-oidc-token');
	persistAccessToken('local-token');
    persistAccessToken('');
    expect(readStoredAccessToken()).toBe('');
  });
});
