import {
  describe,
  it,
  expect
} from 'vitest';
import {
  ProvisionUsernameCollisionError,
  buildProvisionUsernameCandidates,
  shortHomeUserId
} from './signal-server-provision.rules';

describe('signal-server-provision.rules', () => {
  it('derives a stable short id from a home user uuid', () => {
    expect(shortHomeUserId('a3f2b1c4-5678-90ab-cdef-1234567890ab')).toBe('a3f2b1');
  });

  it('orders username candidates with preferred first then suffixed fallback', () => {
    expect(
      buildProvisionUsernameCandidates('alice', 'a3f2b1c4-5678-90ab-cdef-1234567890ab')
    ).toEqual(['alice', 'alice-a3f2b1']);
  });

  it('deduplicates candidates when suffix would repeat preferred username', () => {
    expect(
      buildProvisionUsernameCandidates('alice-a3f2b1', 'a3f2b1c4-5678-90ab-cdef-1234567890ab')
    ).toEqual(['alice-a3f2b1']);
  });

  it('exposes attempted usernames on collision errors', () => {
    const error = new ProvisionUsernameCollisionError('https://signal.example.com', ['alice', 'alice-a3f2b1']);

    expect(error.name).toBe('ProvisionUsernameCollisionError');
    expect(error.serverUrl).toBe('https://signal.example.com');
    expect(error.attemptedUsernames).toEqual(['alice', 'alice-a3f2b1']);
  });
});
