/**
 * Client-side SIP add-on helpers. All calls hit /api/telephone/sip/* which
 * 404s when FEATURE_SIP_ENABLED is off — so any UI using these helpers
 * should first call `getSipFeature()` to decide whether to render.
 */

export interface SipFeatureStatus {
  enabled: boolean;
  platform_enabled: boolean;
}

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

async function jsonFetch<T>(url: string, init?: RequestInit): Promise<T> {
  const res = await fetch(url, { credentials: 'include', ...init });
  const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
  if (!res.ok) throw new Error((data.error as string) || `Request failed: ${res.status}`);
  return data as T;
}

export async function getSipFeature(): Promise<SipFeatureStatus> {
  try {
    return await jsonFetch<SipFeatureStatus>('/api/telephone/sip/feature');
  } catch {
    return { enabled: false, platform_enabled: false };
  }
}

export interface JambonzCredentialsView {
  configured: boolean;
  key_hint: string;
  base_url: string;
  account_sid: string;
  webhook_secret_configured: boolean;
  webhook_secret_hint: string;
  is_active: boolean;
  updated_at: string | null;
  env_fallback: { base_url: boolean; api_key: boolean; account_sid: boolean; webhook_secret: boolean };
}

export async function getJambonzCredentials(): Promise<JambonzCredentialsView> {
  return jsonFetch<JambonzCredentialsView>('/api/telephone/jambonz/credentials');
}

export async function saveJambonzCredentials(input: {
  api_key?: string; base_url: string; account_sid: string; webhook_secret?: string;
}): Promise<{ success: true; key_hint: string }> {
  return jsonFetch('/api/telephone/jambonz/credentials', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(input),
  });
}

export async function deleteJambonzCredentials(): Promise<{ success: true }> {
  return jsonFetch('/api/telephone/jambonz/credentials', { method: 'DELETE' });
}

export async function refreshSipLine(id: string): Promise<{ line: unknown }> {
  return jsonFetch(`/api/telephone/sip/${id}/refresh`, { method: 'POST' });
}

export async function testSipConnection(input: {
  sip_server: string;
  sip_username: string;
  sip_password: string;
  outbound_proxy?: string;
  sip_port?: number;
  sip_transport?: 'UDP' | 'TCP' | 'TLS';
}): Promise<SipTestResult> {
  const res = await fetch('/api/telephone/sip/test', {
    method: 'POST',
    credentials: 'include',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(input),
  });
  const data = (await res.json().catch(() => ({}))) as SipTestResult;
  return { ok: !!data.ok, latencyMs: data.latencyMs, response: data.response, error: data.error };
}
