// Hermes HTTP 客户端 — 向 Hermes 服务器发起同步请求

const SYNC_TIMEOUT_MS = 30000;

// 向 Hermes POST 同步请求
async function postSync(webhookUrl, payload) {
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), SYNC_TIMEOUT_MS);

  try {
    const response = await fetch(webhookUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
      signal: controller.signal,
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.error || `Hermes 返回错误 (${response.status})`);
    }

    return data;
  } catch (err) {
    if (err.name === 'AbortError') {
      throw new Error('Hermes 同步请求超时');
    }
    throw err;
  } finally {
    clearTimeout(timeout);
  }
}

module.exports = { postSync };
