/**
 * Dispatches HTTP requests to registered webhook URLs
 * when SMS events occur.
 */

const axios = require('axios');
const { getActiveWebhooksForEvent } = require('./db');
const log = require('./logger');

/**
 * Fire all matching webhooks for a given event.
 *
 * @param {'received'|'sent'} event
 * @param {object} message - { phone_number, message, direction, status, created_at, id }
 */
async function dispatchWebhooks(event, message) {
  let webhooks;
  try {
    webhooks = getActiveWebhooksForEvent(event, message.phone_number);
  } catch (err) {
    log.error('Webhook', 'Failed to fetch webhooks:', err.message);
    return;
  }

  if (!webhooks.length) {
    log.debug('Webhook', `No webhooks matched for event="${event}" phone="${message.phone_number}"`);
    return;
  }

  const payload = {
    event,
    message: {
      id:           message.id,
      direction:    message.direction,
      phone_number: message.phone_number,
      text:         message.message,
      status:       message.status,
      timestamp:    message.created_at,
    },
  };

  log.debug('Webhook', `Dispatching event="${event}" to ${webhooks.length} hook(s)`);

  for (const hook of webhooks) {
    let extraHeaders = {};
    try {
      if (hook.headers) extraHeaders = JSON.parse(hook.headers);
    } catch { /* ignore bad JSON */ }

    const headers = {
      'Content-Type': 'application/json',
      'User-Agent':   'SMS-Gateway/1.0',
      ...extraHeaders,
    };

    (async () => {
      try {
        const response = await axios({
          method:  (hook.method || 'POST').toUpperCase(),
          url:     hook.url,
          data:    hook.method?.toUpperCase() !== 'GET' ? payload : undefined,
          params:  hook.method?.toUpperCase() === 'GET'  ? { event, phone: message.phone_number, text: message.message } : undefined,
          headers,
          timeout: 10_000,
        });
        log.info('Webhook', `"${hook.name}" → ${hook.url} [${response.status}]`);
      } catch (err) {
        log.warn('Webhook', `"${hook.name}" → ${hook.url} FAILED: ${err.message}`);
      }
    })();
  }
}

module.exports = { dispatchWebhooks };
