/**
 * @vitest-environment happy-dom
 */
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { authHeaders, clearStoredAuth, getStoredAuth, setStoredAuth } from '../api/auth';

describe('auth session helpers', () => {
  beforeEach(() => {
    sessionStorage.clear();
  });

  it('stores and retrieves basic token', () => {
    setStoredAuth('drjones', 'secret');
    expect(getStoredAuth()).toBe(btoa('drjones:secret'));
  });

  it('builds Authorization header when logged in', () => {
    setStoredAuth('user', 'pass');
    expect(authHeaders()).toEqual({ Authorization: `Basic ${btoa('user:pass')}` });
  });

  it('returns empty headers when logged out', () => {
    clearStoredAuth();
    expect(authHeaders()).toEqual({});
  });

  it('getStoredAuth returns null when sessionStorage throws', () => {
    vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
      throw new Error('blocked');
    });
    expect(getStoredAuth()).toBeNull();
  });
});
