/**
 * Telegram channel push.
 *
 * Webhook-style: one-direction POST to Telegram's Bot API. No polling,
 * no command handling. The bot token + channel ID come from env.
 *
 * sendPhoto accepts either a Buffer (multipart upload) or a URL (the
 * Telegram fetcher will pull it). We prefer the URL path when the share
 * card lives behind a stable public endpoint.
 */

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

const BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN;
const CHANNEL_ID = process.env.TELEGRAM_CHANNEL_ID;
const HTTP_TIMEOUT_MS = 12_000;

function configured() {
  return !!(BOT_TOKEN && CHANNEL_ID);
}

function endpoint(method) {
  return `https://api.telegram.org/bot${BOT_TOKEN}/${method}`;
}

async function postToTelegram({ text, imageBuffer, imageUrl, parseMode = 'HTML' } = {}) {
  if (!configured()) {
    return { ok: false, error: 'TELEGRAM_BOT_TOKEN or TELEGRAM_CHANNEL_ID not set' };
  }
  try {
    if (imageBuffer && Buffer.isBuffer(imageBuffer)) {
      const form = new FormData();
      form.append('chat_id', CHANNEL_ID);
      if (text) form.append('caption', text);
      form.append('parse_mode', parseMode);
      form.append('photo', imageBuffer, { filename: 'vyndr.png', contentType: 'image/png' });
      await axios.post(endpoint('sendPhoto'), form, {
        timeout: HTTP_TIMEOUT_MS,
        headers: form.getHeaders(),
        maxContentLength: 8 * 1024 * 1024,
        maxBodyLength: 8 * 1024 * 1024,
      });
      return { ok: true, mode: 'photo-buffer' };
    }
    if (imageUrl) {
      await axios.post(endpoint('sendPhoto'), {
        chat_id: CHANNEL_ID,
        photo: imageUrl,
        caption: text || '',
        parse_mode: parseMode,
      }, { timeout: HTTP_TIMEOUT_MS });
      return { ok: true, mode: 'photo-url' };
    }
    if (text) {
      await axios.post(endpoint('sendMessage'), {
        chat_id: CHANNEL_ID,
        text,
        parse_mode: parseMode,
        disable_web_page_preview: false,
      }, { timeout: HTTP_TIMEOUT_MS });
      return { ok: true, mode: 'text' };
    }
    return { ok: false, error: 'nothing to send' };
  } catch (err) {
    const detail = err?.response?.data || err?.message || 'unknown';
    console.error('[telegram] push failed:', detail);
    return { ok: false, error: typeof detail === 'string' ? detail : JSON.stringify(detail) };
  }
}

module.exports = { postToTelegram, configured };
