/**
 * services/notifier.js
 *
 * Thin wrapper around webhook.dispatch() so any code path that
 * triggers a state change (takedown sent, escalated, removed,
 * finding classified, etc.) can call notify() and have the event
 * fan out to all configured webhooks.
 *
 *   await notify('takedown.removed', { takedown_id: 35, domain: 'erome.com' })
 *
 * Never throws — webhooks are best-effort. A failure is logged to
 * the alert bus but doesn't break the caller's flow.
 */

'use strict';

let _webhook = null;
let _alertBus = null;

function webhook() { if (!_webhook) _webhook = require('./webhook'); return _webhook; }
function alertBus() { if (!_alertBus) _alertBus = require('./alertBus'); return _alertBus; }

async function notify(event, payload) {
  try {
    const r = await webhook().dispatch(event, payload);
    if (r.delivered) {
      // Lightweight breadcrumb in the alert log
      try { alertBus().raise({
        severity: 'info', category: 'webhook',
        title: `Webhook dispatched: ${event}`,
        detail: { event, delivered: r.delivered, failed: r.failed },
        dedupe_key: `webhook:${event}:${Date.now()}`,
      }); } catch (_) {}
    }
    return r;
  } catch (e) {
    try { alertBus().raise({
      severity: 'warn', category: 'webhook',
      title: `Webhook dispatch failed: ${event}`,
      detail: { event, error: String(e.message || e).slice(0, 200) },
    }); } catch (_) {}
    return { delivered: 0, failed: 0, error: e.message };
  }
}

module.exports = { notify };
