/**
 * Handles incoming webhooks from external applications (e.g. uptime-kuma).
 * Looks up the webhook by its URL token, renders the message template,
 * and sends an SMS to the configured phone number.
 */

const { getWebhookByToken, saveMessage, updateMessageStatus } = require('./db');
const teltonika = require('./teltonika');
const log       = require('./logger');

/**
 * Substitute {{key}} and {{key.subkey}} placeholders using values from payload.
 * Unknown keys are replaced with an empty string.
 */
function renderTemplate(template, payload) {
  return template.replace(/\{\{([^}]+)\}\}/g, (_, expr) => {
    const parts = expr.trim().split('.');
    let val = payload;
    for (const part of parts) val = val?.[part];
    return (val !== undefined && val !== null) ? String(val) : '';
  });
}

/**
 * Process an incoming webhook request.
 *
 * @param {string} token   - URL token identifying the webhook
 * @param {object} payload - Parsed JSON body from the incoming request
 * @returns {{ found: boolean, sent?: boolean, message_id?: number, error?: string }}
 */
async function handleIncomingWebhook(token, payload) {
  const hook = getWebhookByToken(token);
  if (!hook) return { found: false };

  if (!hook.active) {
    log.debug('Webhook', `Received request for disabled hook "${hook.name}"`);
    return { found: true, sent: false, error: 'Webhook is disabled' };
  }

  const message = renderTemplate(hook.message_template || '{{msg}}', payload);
  if (!message.trim()) {
    log.warn('Webhook', `Hook "${hook.name}" produced empty message — check template and payload`);
    return { found: true, sent: false, error: 'Empty message after template rendering' };
  }

  log.info('Webhook', `"${hook.name}" triggered → SMS to ${hook.phone_number}: "${message.substring(0, 60)}"`);

  const saved = saveMessage({
    direction:    'sent',
    phone_number: hook.phone_number,
    message,
    status:       'pending',
  });

  try {
    await teltonika.sendSMS(hook.phone_number, message);
    updateMessageStatus(saved.id, 'sent');
    return { found: true, sent: true, message_id: saved.id };
  } catch (err) {
    updateMessageStatus(saved.id, 'failed');
    log.error('Webhook', `SMS send failed for hook "${hook.name}": ${err.message}`);
    return { found: true, sent: false, error: err.message };
  }
}

module.exports = { handleIncomingWebhook, renderTemplate };
