/* Wa by Elivate — small REST client for the static dashboard */
const API_BASE = window.WA_API_BASE || "";

async function apiFetch(path, options = {}) {
  const response = await fetch(`${API_BASE}${path}`, {
    headers: { "Content-Type": "application/json", ...(options.headers || {}) },
    ...options,
  });
  if (!response.ok) {
    const payload = await response.json().catch(() => ({}));
    throw new Error(payload.error || `Request failed: ${response.status}`);
  }
  if (response.status === 204) return null;
  return response.json();
}

window.WaApi = {
  status: () => apiFetch("/api/status"),
  logout: () => apiFetch("/api/logout", { method: "POST" }),
  automations: () => apiFetch("/api/automations"),
  updateAutomation: (id, patch) => apiFetch(`/api/automations/${id}`, { method: "PUT", body: JSON.stringify(patch) }),
  createAutomation: (rule) => apiFetch("/api/automations", { method: "POST", body: JSON.stringify(rule) }),
  testAutomation: (rule) => apiFetch("/api/automations/test", { method: "POST", body: JSON.stringify(rule) }),
  deleteAutomation: (id) => apiFetch(`/api/automations/${id}`, { method: "DELETE" }),
  groups: () => apiFetch("/api/groups"),
  group: (id) => apiFetch(`/api/groups/${encodeURIComponent(id)}`),
  groupAction: (id, payload) => apiFetch(`/api/groups/${encodeURIComponent(id)}/action`, { method: "POST", body: JSON.stringify(payload) }),
  send: (payload) => apiFetch("/api/send", { method: "POST", body: JSON.stringify(payload) }),
  logs: (params = {}) => apiFetch(`/api/logs?${new URLSearchParams(params)}`),
  settings: () => apiFetch("/api/settings"),
  updateSettings: (patch) => apiFetch("/api/settings", { method: "PUT", body: JSON.stringify(patch) }),
  openaiContext: async () => {
    const response = await fetch(`${API_BASE}/api/openai/context`);
    if (!response.ok) throw new Error(`Request failed: ${response.status}`);
    return response.text();
  },
  updateOpenaiContext: (content) => apiFetch("/api/openai/context", { method: "PUT", body: JSON.stringify({ content }) }),
};
