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

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

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

    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 SignalServerCredentialStoreService(new AuthTokenStoreService());
  });

  it('stores and retrieves credentials by normalized server url', () => {
    service.upsertCredential({
      serverUrl: 'https://signal.example.com/',
      userId: 'user-1',
      username: 'alice',
      displayName: 'Alice',
      token: 'token-abc',
      expiresAt: Date.now() + 60_000,
      provisioned: true
    });

    const credential = service.getCredential('https://signal.example.com');

    expect(credential?.userId).toBe('user-1');
    expect(credential?.token).toBe('token-abc');
  });

  it('clears expired credentials on read', () => {
    service.upsertCredential({
      serverUrl: 'https://signal.example.com',
      userId: 'user-1',
      username: 'alice',
      displayName: 'Alice',
      token: 'expired',
      expiresAt: Date.now() - 1,
      provisioned: false
    });

    expect(service.getCredential('https://signal.example.com')).toBeNull();
    expect(service.hasValidCredential('https://signal.example.com')).toBe(false);
  });

  it('removes credentials for a single server url', () => {
    service.upsertCredential({
      serverUrl: 'https://signal-a.example.com',
      userId: 'user-a',
      username: 'alice',
      displayName: 'Alice',
      token: 'token-a',
      expiresAt: Date.now() + 60_000,
      provisioned: true
    });

    service.upsertCredential({
      serverUrl: 'https://signal-b.example.com',
      userId: 'user-b',
      username: 'alice',
      displayName: 'Alice',
      token: 'token-b',
      expiresAt: Date.now() + 60_000,
      provisioned: true
    });

    service.clearCredential('https://signal-a.example.com');

    expect(service.getCredential('https://signal-a.example.com')).toBeNull();
    expect(service.getCredential('https://signal-b.example.com')?.token).toBe('token-b');
  });
});
