import { KafkaJsInstrumentation } from '@opentelemetry/instrumentation-kafkajs';
import { defineIntegration } from '@sentry/core';
import { generateInstrumentOnce } from '../../otel/instrument.js';
import { addOriginToSpan } from '../../utils/addOriginToSpan.js';

const INTEGRATION_NAME = 'Kafka';

const instrumentKafka = generateInstrumentOnce(
  INTEGRATION_NAME,
  () =>
    new KafkaJsInstrumentation({
      consumerHook(span) {
        addOriginToSpan(span, 'auto.kafkajs.otel.consumer');
      },
      producerHook(span) {
        addOriginToSpan(span, 'auto.kafkajs.otel.producer');
      },
    }),
);

const _kafkaIntegration = (() => {
  return {
    name: INTEGRATION_NAME,
    setupOnce() {
      instrumentKafka();
    },
  };
}) ;

/**
 * KafkaJs integration
 *
 * Capture tracing data for KafkaJs.
 */
const kafkaIntegration = defineIntegration(_kafkaIntegration);

export { instrumentKafka, kafkaIntegration };
