export interface CallLog {
  id: string;
  restaurantId: string;
  branchId?: string;
  conversationId?: string;
  callSid?: string;
  direction: 'inbound' | 'outbound';
  fromNumber?: string;
  toNumber?: string;
  status: string;
  durationSeconds: number;
  transcript?: string;
  recordingUrl?: string;
  aiHandled: boolean;
  escalatedToHuman: boolean;
  escalationReason?: string;
  startedAt?: string;
  endedAt?: string;
  createdAt: string;
  updatedAt: string;
  customerName?: string;
  customerPhone?: string;
  customerEmail?: string;
  conversationTopic?: string;
}

export interface CallLogListResponse {
  callLogs: CallLog[];
  total: number;
  page: number;
  limit: number;
  pages: number;
}

export function normalizeCallLog(raw: Record<string, unknown>): CallLog {
  return {
    id: String(raw.id ?? ''),
    restaurantId: String(raw.restaurant_id ?? raw.restaurantId ?? ''),
    branchId: raw.branch_id != null ? String(raw.branch_id) : undefined,
    conversationId: raw.conversation_id != null ? String(raw.conversation_id) : undefined,
    callSid: raw.call_sid != null ? String(raw.call_sid) : undefined,
    direction: (String(raw.direction ?? 'inbound')) as 'inbound' | 'outbound',
    fromNumber: raw.from_number != null ? String(raw.from_number) : undefined,
    toNumber: raw.to_number != null ? String(raw.to_number) : undefined,
    status: String(raw.status ?? 'initiated'),
    durationSeconds: Number(raw.duration_seconds ?? 0),
    transcript: raw.transcript != null ? String(raw.transcript) : undefined,
    recordingUrl: raw.recording_url != null ? String(raw.recording_url) : undefined,
    aiHandled: Boolean(raw.ai_handled ?? true),
    escalatedToHuman: Boolean(raw.escalated_to_human ?? false),
    escalationReason: raw.escalation_reason != null ? String(raw.escalation_reason) : undefined,
    startedAt: raw.started_at != null ? String(raw.started_at) : undefined,
    endedAt: raw.ended_at != null ? String(raw.ended_at) : undefined,
    createdAt: String(raw.created_at ?? raw.createdAt ?? ''),
    updatedAt: String(raw.updated_at ?? raw.updatedAt ?? ''),
    customerName: raw.customer_name != null ? String(raw.customer_name) : undefined,
    customerPhone: raw.customer_phone != null ? String(raw.customer_phone) : undefined,
    customerEmail: raw.customer_email != null ? String(raw.customer_email) : undefined,
    conversationTopic: raw.conversation_topic != null ? String(raw.conversation_topic) : undefined,
  };
}

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

export async function listCallLogs(params: Record<string, string> = {}): Promise<CallLogListResponse> {
  const qs = new URLSearchParams(params).toString();
  const raw = await apiFetch<{ callLogs: Record<string, unknown>[]; total: number; page: number; limit: number; pages: number }>(
    `/api/call-logs${qs ? '?' + qs : ''}`
  );
  return {
    callLogs: (raw.callLogs ?? []).map(normalizeCallLog),
    total: raw.total,
    page: raw.page,
    limit: raw.limit,
    pages: raw.pages,
  };
}

export async function getCallLog(id: string): Promise<{ callLog: CallLog }> {
  const raw = await apiFetch<{ callLog: Record<string, unknown> }>(`/api/call-logs/${id}`);
  return { callLog: normalizeCallLog(raw.callLog) };
}
