import { NodeSDK } from '@opentelemetry/sdk-node';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import { JaegerExporter } from '@opentelemetry/exporter-jaeger';
import { Resource } from '@opentelemetry/resources';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';

/**
 * EN: Configuration interface for distributed tracing setup
 * VI: Interface cấu hình cho việc thiết lập distributed tracing
 */
export interface TracingConfig {
  /** EN: Name of the service for trace identification / VI: Tên service để xác định trace */
  serviceName: string;
  /** EN: Jaeger collector endpoint URL / VI: URL endpoint Jaeger collector */
  jaegerEndpoint?: string;
  /** EN: Enable/disable tracing (default: true) / VI: Bật/tắt tracing (mặc định: true) */
  enabled?: boolean;
}

/**
 * EN: Initialize OpenTelemetry distributed tracing with Jaeger exporter
 * VI: Khởi tạo OpenTelemetry distributed tracing với Jaeger exporter
 *
 * @param config - Tracing configuration / Cấu hình tracing
 * @returns NodeSDK instance or null if tracing is disabled / Instance NodeSDK hoặc null nếu tracing bị tắt
 */
export const initTracing = (config: TracingConfig): NodeSDK | null => {
  // EN: Return null if tracing is explicitly disabled
  // VI: Trả về null nếu tracing bị tắt rõ ràng
  if (config.enabled === false) {
    return null;
  }

  // EN: Create Jaeger exporter if endpoint is provided
  // VI: Tạo Jaeger exporter nếu endpoint được cung cấp
  const jaegerExporter = config.jaegerEndpoint
    ? new JaegerExporter({
        endpoint: config.jaegerEndpoint,
      })
    : undefined;

  // EN: Initialize OpenTelemetry NodeSDK with auto-instrumentations
  // VI: Khởi tạo OpenTelemetry NodeSDK với auto-instrumentations
  const sdk = new NodeSDK({
    resource: new Resource({
      [SemanticResourceAttributes.SERVICE_NAME]: config.serviceName,
    }),
    traceExporter: jaegerExporter,
    instrumentations: [getNodeAutoInstrumentations()],
  });

  // EN: Start the tracing SDK
  // VI: Khởi động tracing SDK
  sdk.start();

  return sdk;
};

// EN: Default export for the initTracing function
// VI: Export default cho hàm initTracing
export default initTracing;
