/**
 * Discord webhook push.
 *
 * One outgoing webhook per channel. No bot library, no gateway connection;
 * just a POST per message. Embeds render the share card via the `image`
 * field — Discord fetches the URL server-side, so the URL must be publicly
 * reachable (n8n can hand the share-card buffer to a CDN if needed).
 */

const axios = require('axios');
const FormData = require('form-data');

const HTTP_TIMEOUT_MS = 10_000;
const VYNDR_GREEN = 0x00D4A0;

const WEBHOOKS = Object.freeze({
  daily:   process.env.DISCORD_WEBHOOK_DAILY   || '',
  results: process.env.DISCORD_WEBHOOK_RESULTS || '',
  alerts:  process.env.DISCORD_WEBHOOK_ALERTS  || '',
  rare:    process.env.DISCORD_WEBHOOK_RARE    || '',
});

function webhookFor(channel) {
  const url = WEBHOOKS[channel];
  if (!url) return null;
  // Don't accept arbitrary user input — only the small set above.
  if (!url.startsWith('https://discord.com/api/webhooks/') &&
      !url.startsWith('https://discordapp.com/api/webhooks/')) {
    return null;
  }
  return url;
}

async function postToDiscord(channel, { text, imageUrl, imageBuffer, color } = {}) {
  const url = webhookFor(channel);
  if (!url) return { ok: false, error: `no webhook for ${channel}` };

  const embed = {
    description: text || '',
    color: color || VYNDR_GREEN,
    image: imageUrl ? { url: imageUrl } : undefined,
    footer: { text: 'VYNDR · vyndr.app' },
    timestamp: new Date().toISOString(),
  };
  const payload = { username: 'VYNDR', embeds: [embed] };

  try {
    if (imageBuffer && Buffer.isBuffer(imageBuffer)) {
      // Multipart with attached PNG. Discord renders attachments inline.
      const form = new FormData();
      form.append('payload_json', JSON.stringify({
        username: 'VYNDR',
        embeds: [{
          description: text || '',
          color: color || VYNDR_GREEN,
          image: { url: 'attachment://vyndr.png' },
          footer: { text: 'VYNDR · vyndr.app' },
          timestamp: new Date().toISOString(),
        }],
      }));
      form.append('file1', imageBuffer, { filename: 'vyndr.png', contentType: 'image/png' });
      await axios.post(url, form, {
        timeout: HTTP_TIMEOUT_MS,
        headers: form.getHeaders(),
        maxContentLength: 8 * 1024 * 1024,
        maxBodyLength: 8 * 1024 * 1024,
      });
      return { ok: true, channel, mode: 'attachment' };
    }
    await axios.post(url, payload, { timeout: HTTP_TIMEOUT_MS });
    return { ok: true, channel, mode: 'embed' };
  } catch (err) {
    const detail = err?.response?.data || err?.message || 'unknown';
    console.error(`[discord:${channel}] push failed:`, detail);
    return { ok: false, error: typeof detail === 'string' ? detail : JSON.stringify(detail) };
  }
}

module.exports = { postToDiscord, webhookFor };
