/**
 * n8n Webhook EventBus Listener
 *
 * Forwards ALL platform events to n8n webhook endpoints.
 * n8n workflows can filter events by type on the receiving end.
 *
 * Configuration:
 *   N8N_WEBHOOK_URLS — comma-separated list of n8n webhook URLs to forward events to.
 *   Each URL receives all events; n8n workflows filter internally.
 *
 * Example .env:
 *   N8N_WEBHOOK_URLS=http://n8n-changemaker:5678/webhook/changemaker-events
 *
 * Feature guard: N8N_WEBHOOK_URLS must be set (non-empty).
 */

import { eventBus } from '../event-bus.service';
import { env } from '../../config/env';
import { logger } from '../../utils/logger';

function getWebhookUrls(): string[] {
  const raw = (env as unknown as Record<string, string>).N8N_WEBHOOK_URLS || '';
  if (!raw) return [];
  return raw.split(',').map(u => u.trim()).filter(Boolean);
}

async function forwardToN8n(event: string, payload: unknown): Promise<void> {
  const urls = getWebhookUrls();
  if (urls.length === 0) return;

  for (const url of urls) {
    try {
      await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          event,
          payload,
          timestamp: new Date().toISOString(),
          source: 'changemaker-lite',
        }),
        signal: AbortSignal.timeout(5000),
      });
    } catch (err) {
      logger.debug(`n8n webhook delivery failed for ${event} → ${url}:`, err);
    }
  }
}

export function registerN8nWebhookListener(): void {
  // Subscribe to ALL events using wildcard pattern
  eventBus.subscribePattern('*', 'n8n:webhook-emitter', (event, payload) => {
    forwardToN8n(event, payload);
  });
}
