import {
  describe,
  it,
  expect
} from 'vitest';
import type { Room } from '../../shared-kernel';
import { buildServerRegistrationPayload } from './server-registration.rules';

function makeRoom(overrides: Partial<Room> = {}): Room {
  return {
    id: 'room-1',
    name: 'My Server',
    description: 'desc',
    topic: 'gaming',
    hostId: 'user-1',
    hasPassword: false,
    isPrivate: false,
    createdAt: 1,
    userCount: 1,
    maxUsers: 50,
    channels: [{ id: 'c1', name: 'general', type: 'text', position: 0 }],
    ...overrides
  } as Room;
}

describe('buildServerRegistrationPayload', () => {
  it('uses oderId as the owner public key when present', () => {
    const payload = buildServerRegistrationPayload(
      makeRoom(),
      { id: 'user-1', oderId: 'oder-1', displayName: 'Alice' },
      ''
    );

    expect(payload.ownerId).toBe('user-1');
    expect(payload.ownerPublicKey).toBe('oder-1');
  });

  it('falls back to the user id when oderId is missing so the server accepts the registration', () => {
    const payload = buildServerRegistrationPayload(
      makeRoom(),
      { id: 'user-1', oderId: undefined, displayName: 'Alice' },
      ''
    );

    // Server returns 400 "Missing required fields" without a truthy ownerPublicKey.
    expect(payload.ownerPublicKey).toBe('user-1');
  });

  it('normalizes password presence', () => {
    const withPw = buildServerRegistrationPayload(
      makeRoom(),
      { id: 'user-1', oderId: 'oder-1', displayName: 'Alice' },
      'secret'
    );
    const withoutPw = buildServerRegistrationPayload(
      makeRoom(),
      { id: 'user-1', oderId: 'oder-1', displayName: 'Alice' },
      ''
    );

    expect(withPw.password).toBe('secret');
    expect(withPw.hasPassword).toBe(true);
    expect(withoutPw.password).toBeNull();
    expect(withoutPw.hasPassword).toBe(false);
  });

  it('carries the room channels and identity through to the payload', () => {
    const payload = buildServerRegistrationPayload(
      makeRoom({ id: 'room-9', name: 'Beta' }),
      { id: 'user-2', oderId: 'oder-2', displayName: 'Bob' },
      ''
    );

    expect(payload.id).toBe('room-9');
    expect(payload.name).toBe('Beta');
    expect(payload.hostName).toBe('Bob');
    expect(payload.channels).toHaveLength(1);
  });
});
