/**
 * KafkaAdapter — optional Kafka producer activated when KAFKA_BROKERS env var is set.
 * Returns null if KAFKA_BROKERS is not configured.
 *
 * The producer connects at application startup. When KAFKA_BROKERS is absent the
 * EventPublisher operates in webhook-only mode and Kafka delivery is silently skipped.
 */

import { Kafka, Producer as KafkaProducer } from 'kafkajs';

/**
 * Creates and connects a KafkaJS producer.
 * Returns null when the KAFKA_BROKERS environment variable is not set.
 *
 * @returns A connected KafkaProducer, or null if Kafka is not configured.
 */
export async function createKafkaProducer(): Promise<KafkaProducer | null> {
  const brokers = process.env['KAFKA_BROKERS'];
  if (!brokers) return null;

  const kafka = new Kafka({
    clientId: 'agentidp',
    brokers: brokers.split(','),
  });

  const producer = kafka.producer();
  await producer.connect();
  return producer;
}
