/**
 * config.ts — per-engineer connection settings for the go.mindserv.co server.
 *
 * Values proven working via the browser test client:
 *   - WSS  wss://go.mindserv.co:8089/ws   (transport-wss + http.conf TLS)
 *   - each engineer registers as an agent (agent1..agent100 / agentNpass)
 *   - outbound: prepend "80" -> routes via trunk2 (live Ishan carrier)
 *   - outbound caller ID sent as the X-CLI SIP header
 */
/** ICE server shape (react-native-webrtc accepts this same object). */
export interface IceServer {
  urls: string;
  username?: string;
  credential?: string;
}

export interface SipConfig {
  wsServer: string;          // 'wss://go.mindserv.co:8089/ws'
  domain: string;            // 'go.mindserv.co'
  extension: string;         // SIP username, e.g. 'agent2'
  password: string;          // SIP secret, e.g. 'agent2pass'
  displayName: string;
  iceServers: IceServer[];
  /** Prefix that routes a 10-digit mobile through the live trunk (trunk2 = "80"). */
  dialPrefix: string;        // '80'
  /** Caller ID sent to the carrier via the X-CLI header (a valid DID). */
  outboundCli: string;       // '00917969812708'
}

export const DEFAULT_ICE: IceServer[] = [
  { urls: 'stun:stun.l.google.com:19302' },
  // Add TURN here for engineers on carrier CGNAT (matches coturn if you run one).
];

export const DEFAULTS = {
  wsServer: 'wss://go.mindserv.co:8089/ws',
  domain: 'go.mindserv.co',
  dialPrefix: '80',
  outboundCli: '00917969812708',
};

export const buildConfig = (over: Partial<SipConfig>): SipConfig => ({
  wsServer: DEFAULTS.wsServer,
  domain: DEFAULTS.domain,
  extension: '',
  password: '',
  displayName: 'Field Engineer',
  iceServers: DEFAULT_ICE,
  dialPrefix: DEFAULTS.dialPrefix,
  outboundCli: DEFAULTS.outboundCli,
  ...over,
});

/**
 * Format a dialed number to what [trunk-out] expects.
 *   - already "80…"/"90…" prefixed  -> unchanged
 *   - 10-digit Indian mobile (6-9…)  -> prepend dialPrefix ("80") => trunk2
 *   - 0 + 10-digit                   -> drop the 0, prepend dialPrefix
 *   - anything else (agent name, ext)-> unchanged (internal call)
 */
export function formatOutbound(input: string, dialPrefix = DEFAULTS.dialPrefix): string {
  const raw = input.trim();
  const d = raw.replace(/\D/g, '');
  if (/^(80|90)\d{10}$/.test(d)) return d;          // already prefixed
  if (/^[6-9]\d{9}$/.test(d)) return dialPrefix + d; // bare 10-digit mobile
  if (/^0[6-9]\d{9}$/.test(d)) return dialPrefix + d.slice(1);
  return raw; // agentN / short extension -> dial as typed
}
