import { OfflineQueueRepository } from '../../infrastructure/offline-queue.repository';

describe('OfflineMessageQueueService storage contract', () => {
  let repository: OfflineQueueRepository;

  beforeEach(() => {
    installLocalStorageMock();
    repository = new OfflineQueueRepository();
  });

  it('should enqueue messages', async () => {
    await repository.enqueue('alice', 'message-1');
    await repository.enqueue('alice', 'message-1');

    expect(await repository.load('alice')).toEqual(['message-1']);
  });

  it('should retry on reconnect', async () => {
    await repository.enqueue('alice', 'message-1');
    await repository.enqueue('alice', 'message-2');

    expect(await repository.load('alice')).toEqual(['message-1', 'message-2']);
  });

  it('should clear delivered messages', async () => {
    await repository.enqueue('alice', 'message-1');
    await repository.remove('alice', 'message-1');

    expect(await repository.load('alice')).toEqual([]);
  });
});

function installLocalStorageMock(): void {
  const values = new Map<string, string>();

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