import { FriendRepository } from '../../infrastructure/friend.repository';

describe('FriendService storage contract', () => {
  let repository: FriendRepository;

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

  it('should add friend', async () => {
    await repository.addFriend('alice', { userId: 'bob', addedAt: 10 });

    expect(await repository.loadFriends('alice')).toEqual([{ userId: 'bob', addedAt: 10 }]);
  });

  it('should remove friend', async () => {
    await repository.addFriend('alice', { userId: 'bob', addedAt: 10 });
    await repository.removeFriend('alice', 'bob');

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

  it('should persist friends', async () => {
    await repository.addFriend('alice', { userId: 'bob', addedAt: 10 });
    const reloadedRepository = new FriendRepository();

    expect(await reloadedRepository.loadFriends('alice')).toEqual([{ userId: 'bob', addedAt: 10 }]);
  });
});

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