/**
 * sip-test.service.ts — verify a SIP trunk's credentials before saving.
 *
 * Returns the structured result documented in Task #312:
 *   { ok, latencyMs, response, error? }
 */
import { getJambonzCreds, testCarrier } from '@server/services/telephone/jambonz/jambonz.service';

export interface SipTestInput {
  sip_server: string;
  sip_username: string;
  sip_password: string;
  outbound_proxy?: string;
  sip_port?: number;
  sip_transport?: 'UDP' | 'TCP' | 'TLS';
}

export interface SipTestResult {
  ok: boolean;
  latencyMs: number;
  response?: unknown;
  error?: string;
}

export async function testSipConnection(restaurantId: string, input: SipTestInput): Promise<SipTestResult> {
  const startedAt = Date.now();
  const creds = await getJambonzCreds(restaurantId);
  if (!creds) {
    return {
      ok: false,
      latencyMs: Date.now() - startedAt,
      error: 'jambonz is not configured. Set JAMBONZ_BASE_URL, JAMBONZ_API_KEY and JAMBONZ_ACCOUNT_SID, or save jambonz credentials for this restaurant.',
    };
  }
  const result = await testCarrier(creds, input);
  return {
    ok: result.ok,
    latencyMs: result.latencyMs,
    response: result.response,
    error: result.ok ? undefined : result.error,
  };
}
