import {
  describe,
  it,
  expect,
  beforeEach
} from 'vitest';
import { AuthTokenStoreService } from './auth-token-store.service';

describe('AuthTokenStoreService', () => {
  let service: AuthTokenStoreService;

  const storage = new Map<string, string>();

  beforeEach(() => {
    storage.clear();
    vi.stubGlobal('localStorage', {
      getItem: (key: string) => storage.get(key) ?? null,
      setItem: (key: string, value: string) => { storage.set(key, value); },
      removeItem: (key: string) => { storage.delete(key); },
      clear: () => { storage.clear(); }
    });

    service = new AuthTokenStoreService();
  });

  it('reports whether any non-expired token remains', () => {
    expect(service.hasAnyValidToken()).toBe(false);

    service.setToken('http://localhost:3001', 'token-abc', Date.now() + 60_000);

    expect(service.hasAnyValidToken()).toBe(true);
  });

  it('stores and resolves tokens by signaling server url', () => {
    service.setToken('http://localhost:3001', 'token-abc', Date.now() + 60_000);

    expect(service.getToken('http://localhost:3001')).toBe('token-abc');
    expect(service.findTokenForApiUrl('http://localhost:3001/api/servers')).toBe('token-abc');
  });

  it('clears expired tokens on read', () => {
    service.setToken('http://localhost:3001', 'expired-token', Date.now() - 1);

    expect(service.getToken('http://localhost:3001')).toBeNull();
  });
});
