export async function agentRequest(node, path, options = {}) {
  const response = await fetch(`${node.baseUrl}/api${path}`, {
    method: options.method || 'GET',
    headers: {
      Authorization: `Bearer ${node.token}`,
      'Content-Type': 'application/json',
      ...(options.headers || {}),
    },
    body: options.body ? JSON.stringify(options.body) : undefined,
    signal: AbortSignal.timeout(options.timeout || 20000),
  });

  const text = await response.text();
  const data = text ? JSON.parse(text) : null;
  if (!response.ok) {
    const error = new Error(data?.error || `Agent request failed with ${response.status}`);
    error.status = response.status;
    throw error;
  }
  return data;
}

export function publicNode(node) {
  return {
    id: node.id,
    name: node.name,
    baseUrl: node.baseUrl,
    enabled: node.enabled,
    lastHealthStatus: node.lastHealthStatus,
    lastHealthAt: node.lastHealthAt,
    createdAt: node.createdAt,
    updatedAt: node.updatedAt,
  };
}
