/**
 * Browser device registration.
 *
 * SIP device registration is now handled entirely by the Rust proxy-engine.
 * This module only handles browser softphone registration via WebSocket.
 */

import { createHash } from 'node:crypto';

/** Hash a string to a 6-char hex ID. */
export function shortHash(input: string): string {
  return createHash('sha256').update(input).digest('hex').slice(0, 6);
}

// ---------------------------------------------------------------------------
// Browser device registration
// ---------------------------------------------------------------------------

const browserDevices = new Map<string, { deviceId: string; displayName: string; remoteIp: string }>();

/**
 * Register a browser softphone as a device.
 */
export function registerBrowserDevice(sessionId: string, userAgent?: string, remoteIp?: string): void {
  let browserName = 'Browser';
  if (userAgent) {
    if (userAgent.includes('Firefox/')) browserName = 'Firefox';
    else if (userAgent.includes('Edg/')) browserName = 'Edge';
    else if (userAgent.includes('Chrome/')) browserName = 'Chrome';
    else if (userAgent.includes('Safari/') && !userAgent.includes('Chrome/')) browserName = 'Safari';
  }

  browserDevices.set(sessionId, {
    deviceId: `browser-${shortHash(sessionId)}`,
    displayName: browserName,
    remoteIp: remoteIp || '127.0.0.1',
  });
}

/**
 * Unregister a browser softphone (on WebSocket close).
 */
export function unregisterBrowserDevice(sessionId: string): void {
  browserDevices.delete(sessionId);
}
