// api.jsx — typed-ish fetch helpers for the backend REST API. window.API.
const API_BASE = "/api";

async function req(method, path, body) {
  const opts = { method, headers: {} };
  if (body !== undefined) {
    opts.headers["Content-Type"] = "application/json";
    opts.body = JSON.stringify(body);
  }
  const res = await fetch(API_BASE + path, opts);
  if (!res.ok) {
    let bodyObj = null, detail = "";
    try { bodyObj = await res.json(); detail = JSON.stringify(bodyObj); } catch {}
    // Prefer the server's human-readable message/error so callers never surface
    // raw JSON to the user (e.g. WhatsApp pairing failures).
    const friendly = bodyObj && (bodyObj.message || bodyObj.error);
    const err = new Error(friendly || `API ${method} ${path} failed (${res.status}) ${detail}`);
    err.status = res.status; err.body = bodyObj;
    throw err;
  }
  if (res.status === 204) return null;
  return res.json();
}

window.API = {
  bootstrap: () => req("GET", "/bootstrap"),
  health: () => req("GET", "/health"),

  contacts: {
    list: () => req("GET", "/contacts"),
    get: (id) => req("GET", `/contacts/${id}`),
    create: (body) => req("POST", "/contacts", body),
    update: (id, patch) => req("PATCH", `/contacts/${id}`, patch),
    remove: (id) => req("DELETE", `/contacts/${id}`),
    addNote: (id, text) => req("POST", `/contacts/${id}/notes`, { text }),
    importRows: (body) => req("POST", "/contacts/import", body),
    // ---- Lead Intelligence: import / dedup / delete-all / analysis ----
    importFile: (filename, dataBase64) => req("POST", "/contacts/import-file", { filename, dataBase64 }),
    importPreview: (arg) => req("POST", "/contacts/import-preview", Array.isArray(arg) ? { rows: arg } : (arg || {})),
    importCommit: (body) => req("POST", "/contacts/import-commit", body),
    duplicates: () => req("GET", "/contacts/duplicates"),
    cleanDuplicates: () => req("POST", "/contacts/clean-duplicates", {}),
    deleteAll: (confirm) => req("POST", "/contacts/delete-all", { confirm }),
    intelligence: (id) => req("GET", `/contacts/${id}/intelligence`),
    analyzeWebsite: (id) => req("POST", `/contacts/${id}/analyze-website`, {}),
    websiteJob: (id) => req("GET", `/contacts/${id}/website-job`),
    analyzeMaps: (id) => req("POST", `/contacts/${id}/analyze-maps`, {}),
    mapsJob: (id) => req("GET", `/contacts/${id}/maps-job`),
    setMeeting: (id, body) => req("POST", `/contacts/${id}/meeting`, body || {}),
    bulkAnalyze: (body) => req("POST", "/contacts/bulk-analyze", body || {}),
    analysisStatus: () => req("GET", "/analysis/status"),
    retryFailedAnalysis: (kind) => req("POST", "/analysis/retry-failed", { kind }),
    cancelQueuedAnalysis: (kind) => req("POST", "/analysis/cancel-queued", { kind }),
    salesBrief: (id) => req("POST", `/contacts/${id}/sales-brief`, {}),
    addToAgentMemory: (id) => req("POST", `/contacts/${id}/add-to-agent-memory`, {}),
    toCampaign: (id) => req("POST", `/contacts/${id}/to-campaign`, {}),
  },
  campaigns: {
    list: () => req("GET", "/campaigns"),
    create: (body) => req("POST", "/campaigns", body),
    update: (id, patch) => req("PATCH", `/campaigns/${id}`, patch),
    remove: (id) => req("DELETE", `/campaigns/${id}`),
  },
  agents: {
    list: () => req("GET", "/agents"),
    create: (body) => req("POST", "/agents", body),
    update: (id, patch) => req("PATCH", `/agents/${id}`, patch),
    remove: (id) => req("DELETE", `/agents/${id}`),
  },
  sessions: {
    list: () => req("GET", "/sessions"),
    create: (body) => req("POST", "/sessions", body),
    update: (id, patch) => req("PATCH", `/sessions/${id}`, patch),
  },
  settings: {
    get: () => req("GET", "/settings"),
    update: (patch) => req("PATCH", "/settings", patch),
  },
  dashboard: () => req("GET", "/dashboard"),

  conversations: {
    list: () => req("GET", "/conversations"),
    get: (id) => req("GET", `/conversations/${id}`),
    regenerate: (id) => req("POST", `/conversations/${id}/regenerate`, {}),
    approve: (id, text) => req("POST", `/conversations/${id}/approve`, { text }),
    reject: (id, feedback) => req("POST", `/conversations/${id}/reject`, feedback ? { feedback } : {}),
    feedback: (id, text, reason) => req("POST", `/conversations/${id}/feedback`, { text, reason }),
    send: (id, text, as) => req("POST", `/conversations/${id}/send`, { text, as }),
    takeover: (id, taken) => req("POST", `/conversations/${id}/takeover`, { taken }),
    retranscribe: (id, mid) => req("POST", `/conversations/${id}/messages/${mid}/retranscribe`, {}),
  },
  ai: {
    status: () => req("GET", "/ai/status"),
    draft: (body) => req("POST", "/ai/draft", body),
    opener: (body) => req("POST", "/ai/opener", body),
    generateDrafts: (body) => req("POST", "/ai/generate-drafts", body),
    // provider key management + model registry + tests (keys never returned)
    providers: () => req("GET", "/ai/providers"),
    models: (provider) => req("GET", `/ai/models?provider=${encodeURIComponent(provider)}`),
    saveKey: (provider, key) => req("POST", `/ai/providers/${provider}/key`, { key }),
    clearKey: (provider) => req("DELETE", `/ai/providers/${provider}/key`),
    testProvider: (provider, model) => req("POST", `/ai/providers/${provider}/test`, model ? { model } : {}),
    recommend: (provider, mode) => req("POST", "/ai/model-routing/recommend", { provider, mode }),
    agentModelConfig: (agentKey, body) => req("PATCH", `/ai/agents/${agentKey}/model-config`, body),
    testAgent: (agentKey) => req("POST", `/ai/agents/${agentKey}/test`, {}),
  },

  // ---- Core Dynamic Workflow ----
  workflow: {
    agents: () => req("GET", "/workflow/agents"),
    run: (leadId, trigger) => req("POST", "/workflow/run", { leadId, trigger }),
    runAgent: (leadId, agentKey, runId) => req("POST", "/workflow/agent", { leadId, agentKey, runId }),
    retry: (agentRunId) => req("POST", "/workflow/retry", { agentRunId }),
    status: (leadId) => req("GET", `/workflow/status/${leadId}`),
    runs: (leadId) => req("GET", `/workflow/runs${leadId ? `?leadId=${leadId}` : ""}`),
    research: (leadId) => req("GET", `/workflow/research/${leadId}`),
    offer: (leadId) => req("GET", `/workflow/offer/${leadId}`),
    whatsapp: (leadId) => req("POST", "/workflow/whatsapp", { leadId }),
    insights: () => req("GET", "/workflow/insights"),
    salesLearning: () => req("GET", "/workflow/sales-learning"),
    analyze: () => req("POST", "/workflow/analyze", {}),
    discover: (body) => req("POST", "/workflow/discover", body),
  },

  // ---- Knowledge Base ----
  knowledge: {
    list: () => req("GET", "/knowledge"),
    get: (id) => req("GET", `/knowledge/${id}`),
    update: (id, patch) => req("PATCH", `/knowledge/${id}`, patch),
    platforms: () => req("GET", "/knowledge/platforms"),
  },

  // ---- Follow-ups ----
  followups: {
    list: (leadId) => req("GET", `/followups${leadId ? `?leadId=${leadId}` : ""}`),
    create: (body) => req("POST", "/followups", body),
    update: (id, patch) => req("PATCH", `/followups/${id}`, patch),
  },

  // ---- WhatsApp ----
  whatsapp: {
    status: () => req("GET", "/whatsapp/status"),
    send: (body) => req("POST", "/whatsapp/send", body),
    qr: (sender) => req("GET", `/whatsapp/qr${sender ? `?sender=${encodeURIComponent(sender)}` : ""}`),
    reconnect: (sender) => req("POST", "/whatsapp/reconnect", sender ? { sender } : {}),
    logout: (sender) => req("POST", "/whatsapp/logout", sender ? { sender } : {}),
    pairingCode: (phoneNumber) => req("POST", "/whatsapp/pairing-code", { phoneNumber }),
    sendTest: (body) => req("POST", "/whatsapp/send-test", body || {}),
    // ---- multi-line ----
    lines: () => req("GET", "/whatsapp/lines"),
    linesHealth: () => req("GET", "/whatsapp/lines/health"),
    createLine: (body) => req("POST", "/whatsapp/lines", body),
    updateLine: (id, patch) => req("PATCH", `/whatsapp/lines/${id}`, patch),
    deleteLine: (id) => req("DELETE", `/whatsapp/lines/${id}`),
    lineQr: (id) => req("POST", `/whatsapp/lines/${id}/connect-qr`, {}),
    linePairing: (id, phoneNumber) => req("POST", `/whatsapp/lines/${id}/pairing-code`, { phoneNumber }),
    lineReconnect: (id) => req("POST", `/whatsapp/lines/${id}/reconnect`, {}),
    lineDisconnect: (id) => req("POST", `/whatsapp/lines/${id}/disconnect`, {}),
    lineStatus: (id) => req("GET", `/whatsapp/lines/${id}/status`),
  },

  // ---- High-volume messaging queue ----
  messaging: {
    metrics: () => req("GET", "/messaging/metrics"),
    senders: () => req("GET", "/messaging/senders"),
    updateSender: (id, patch) => req("PATCH", `/messaging/senders/${id}`, patch),
    queue: (q) => req("GET", `/messaging/queue${q ? "?" + q : ""}`),
    job: (id) => req("GET", `/messaging/job/${id}`),
    plan: (body) => req("POST", "/messaging/plan", body),
    campaign: (body) => req("POST", "/messaging/campaign", body),
    enqueue: (body) => req("POST", "/messaging/enqueue", body),
    dispatch: (body) => req("POST", "/messaging/dispatch", body || {}),
    retry: (ids) => req("POST", "/messaging/retry", ids ? { ids } : {}),
    cancel: (ids) => req("POST", "/messaging/cancel", { ids }),
    // A1 — resolve crash-window 'uncertain' sends: resolution "retry"|"sent"|"cancel".
    resolveUncertain: (ids, resolution) => req("POST", "/messaging/resolve-uncertain", { ids, resolution }),
    diagnostics: () => req("GET", "/diagnostics"),
  },

  // ---- Retargeting (CRM + finished-campaign re-engagement) ----
  retargeting: {
    crmRules: () => req("GET", "/retargeting/crm-rules"),
    campaigns: () => req("GET", "/retargeting/campaigns"),
    campaignRules: (id) => req("GET", `/retargeting/campaigns/${id}/rules`),
    preview: (body) => req("POST", "/retargeting/preview", body),
    createCampaign: (body) => req("POST", "/retargeting/create-campaign", body),
  },

  // ---- Campaign Builder (audiences / filters / saved audiences / templates) ----
  campaignBuilder: {
    filters: () => req("GET", "/campaign-builder/filters"),
    previewAudience: (filters) => req("POST", "/campaign-builder/audience/preview", { filters }),
    audiences: () => req("GET", "/campaign-builder/audiences"),
    createAudience: (body) => req("POST", "/campaign-builder/audiences", body),
    updateAudience: (id, patch) => req("PATCH", `/campaign-builder/audiences/${id}`, patch),
    deleteAudience: (id) => req("DELETE", `/campaign-builder/audiences/${id}`),
    templates: () => req("GET", "/campaign-builder/templates"),
    template: (id) => req("GET", `/campaign-builder/templates/${id}`),
    applyTemplate: (id, body) => req("POST", `/campaign-builder/templates/${id}/apply`, body || {}),
  },

  // ---- Sales ops (custom requests + escalations) ----
  customRequests: {
    list: (q) => req("GET", `/custom-requests${q ? "?" + q : ""}`),
    create: (body) => req("POST", "/custom-requests", body),
    update: (id, patch) => req("PATCH", `/custom-requests/${id}`, patch),
  },
  escalations: {
    list: (q) => req("GET", `/escalations${q ? "?" + q : ""}`),
    get: (id) => req("GET", `/escalations/${id}`),
    create: (body) => req("POST", "/escalations", body),
    update: (id, patch) => req("PATCH", `/escalations/${id}`, patch),
  },

  // ---- Briefs / search / notifications / metrics ----
  briefs: {
    list: (q) => req("GET", `/briefs${q ? "?" + q : ""}`),
    create: (body) => req("POST", "/briefs", body),
    update: (id, patch) => req("PATCH", `/briefs/${id}`, patch),
  },
  search: (q) => req("GET", `/search?q=${encodeURIComponent(q)}`),
  notifications: () => req("GET", "/notifications"),
  markNotificationsRead: (body) => req("POST", "/notifications/read", body || {}),

  // ---- Auth (only active when the server runs with MAXAB_AUTH=1) ----
  auth: {
    me: () => req("GET", "/auth/me"),
    login: (body) => req("POST", "/auth/login", body),
    logout: () => req("POST", "/auth/logout", {}),
    users: {
      list: () => req("GET", "/auth/users"),
      create: (body) => req("POST", "/auth/users", body),
      remove: (id) => req("DELETE", `/auth/users/${id}`),
    },
  },
  metrics: {
    campaigns: () => req("GET", "/metrics/campaigns"),
    agents: () => req("GET", "/metrics/agents"),
  },
};
