import {
  describe,
  it,
  expect
} from 'vitest';
import { resolveSignalIdentity } from './signal-server-credential-resolution.rules';

describe('resolveSignalIdentity', () => {
  const homeUser = {
    id: 'home-user-1',
    displayName: 'Alice',
    homeSignalServerUrl: 'https://signal.example.com'
  };

  it('prefers the per-signal credential when present', () => {
    const resolved = resolveSignalIdentity(
      { userId: 'provisioned-1', token: 'cred-token', displayName: 'Alice On Foreign' },
      { token: 'legacy-token' },
      homeUser
    );

    expect(resolved).toEqual({
      userId: 'provisioned-1',
      token: 'cred-token',
      displayName: 'Alice On Foreign',
      homeSignalServerUrl: 'https://signal.example.com'
    });
  });

  it('falls back to the legacy session token using the home identity when no credential exists', () => {
    const resolved = resolveSignalIdentity(
      null,
      { token: 'legacy-token' },
      homeUser
    );

    expect(resolved).toEqual({
      userId: 'home-user-1',
      token: 'legacy-token',
      displayName: 'Alice',
      homeSignalServerUrl: 'https://signal.example.com'
    });
  });

  it('returns null when neither a credential nor a legacy token is available', () => {
    expect(resolveSignalIdentity(null, null, homeUser)).toBeNull();
  });

  it('does not fall back to the legacy token without a known home user id', () => {
    expect(resolveSignalIdentity(null, { token: 'legacy-token' }, null)).toBeNull();
    expect(
      resolveSignalIdentity(null, { token: 'legacy-token' }, { displayName: 'Alice' })
    ).toBeNull();
  });
});
