import type { Room } from '../../shared-kernel';
import { defaultChannels } from './room-channels.defaults';

export interface ServerRegistrationOwner {
  id: string;
  oderId?: string;
  displayName: string;
}

export interface ServerRegistrationPayload {
  id: string;
  name: string;
  description?: string;
  ownerId: string;
  ownerPublicKey: string;
  hostName: string;
  password: string | null;
  hasPassword: boolean;
  isPrivate: boolean;
  userCount: number;
  maxUsers: number;
  icon?: string;
  iconUpdatedAt?: number;
  tags: string[];
  channels: NonNullable<Room['channels']>;
}

/**
 * Build the `/api/servers` registration body for a freshly created room.
 *
 * `ownerPublicKey` must be truthy or the server rejects the request with
 * `400 Missing required fields`, which (because registration is fire-and-forget)
 * leaves the creator inside a room view for a server that was never persisted.
 * `oderId` can be absent on restored sessions, so fall back to the user id the
 * same way the rest of the app resolves an actor identity (`oderId || id`).
 */
export function buildServerRegistrationPayload(
  room: Room,
  owner: ServerRegistrationOwner,
  normalizedPassword: string
): ServerRegistrationPayload {
  return {
    id: room.id,
    name: room.name,
    description: room.description,
    ownerId: owner.id,
    ownerPublicKey: owner.oderId || owner.id,
    hostName: owner.displayName,
    password: normalizedPassword || null,
    hasPassword: normalizedPassword.length > 0,
    isPrivate: room.isPrivate ?? false,
    userCount: room.userCount,
    maxUsers: room.maxUsers || 50,
    icon: room.icon,
    iconUpdatedAt: room.iconUpdatedAt,
    tags: [],
    channels: room.channels ?? defaultChannels()
  };
}
