import { hmacSha256Hex } from './crypto.js';
import { config } from './config.js';

export async function sendRewardsRequest(payload) {
  if (!config.apiBaseUrl || !config.rewardsEndpointPath) {
    throw new Error('HTTP rewards fallback not configured (API_BASE_URL / REWARDS_ENDPOINT_PATH missing)');
  }
  const body = JSON.stringify(payload);
  const ts = String(Date.now());
  const msg = ts + '.' + body;
  const sig = hmacSha256Hex(config.sharedSecret, msg);

  const url = config.apiBaseUrl + config.rewardsEndpointPath;
  const res = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-OG-Timestamp': ts,
      'X-OG-Signature': `sha256=${sig}`,
    },
    body,
  });

  const text = await res.text();
  let json;
  try { json = JSON.parse(text); } catch { json = { raw: text }; }

  if (!res.ok) {
    const err = new Error(`Rewards endpoint error ${res.status}`);
    err.details = json;
    throw err;
  }
  return json;
}
