/**
 * Thin client for the local share-card endpoint.
 *
 * In-process callers can just call the renderer directly; we hit the route
 * so caching + rate-limit semantics stay consistent with how external
 * channels (n8n, email) will request the same cards.
 */

const axios = require('axios');

const API_BASE = process.env.SHARE_CARD_API_BASE || process.env.API_BASE_URL || 'http://localhost:4000';
const TIMEOUT_MS = 12_000;

async function buildCard({ type, format = 'twitter', payload, raw = false }) {
  const res = await axios.post(`${API_BASE}/api/share-card${raw ? '?svg=1' : ''}`, { type, format, ...payload }, {
    responseType: 'arraybuffer',
    timeout: TIMEOUT_MS,
    validateStatus: (s) => s >= 200 && s < 500,
  });
  if (res.status >= 400) {
    const err = new Error(`share-card responded ${res.status}`);
    err.detail = res.data?.toString?.('utf8');
    throw err;
  }
  return {
    buffer: Buffer.from(res.data),
    contentType: res.headers['content-type'] || 'image/png',
    cached: res.headers['x-cache'] === 'HIT',
  };
}

/**
 * Build a public URL where a card lives (or will be once the static-CDN
 * adapter is wired). Today the card is consumed directly by Telegram /
 * Discord / email so we don't always need a hosted URL — but generators
 * return one so downstream callers can render `<img src=...>` markup.
 */
function publicCardUrl({ type, format = 'twitter', payload }) {
  const qs = new URLSearchParams({
    type, format,
    p: Buffer.from(JSON.stringify(payload)).toString('base64url'),
  }).toString();
  const base = process.env.PUBLIC_SHARE_CARD_BASE || `${API_BASE}/api/share-card`;
  return `${base}?${qs}`;
}

module.exports = { buildCard, publicCardUrl };
