import tracer, { TracerOptions } from 'dd-trace';

if (process.env.NODE_ENV === 'production' && process.env.DD_TRACE_ENABLED === 'true') {
  // List of options available to the tracer: https://datadoghq.dev/dd-trace-js/interfaces/export_.TracerOptions.html
  const apmConfig: TracerOptions = { logInjection: false, profiling: false, sampleRate: 0 };

  if (process.env.DD_APM_ENABLED == 'true') {
    apmConfig.logInjection = true;
    apmConfig.sampleRate = 1;
  } else {
    // The "enable tracing" boolean is not exposed as part of the TracerOptions so we
    // have to do so through env vars. Setting here instead of in services' config
    // to avoid too many env vars to "flip" when enabling / disabling APM.
    process.env.DD_TRACING_ENABLED = 'false';
  }

  // Profiling is extra $$$ so we're setting it as an "extra" when needed
  if (process.env.DD_APM_PROFILING_ENABLED == 'true') {
    apmConfig.profiling = true;
  }

  const tags: { [key: string]: any } = {};
  // Using DD_TRACE_AGENT_URL as a hack to know if we're running inside of Kubernetes
  // since this variable is not needed in Elastic Beanstalk of Lambda
  if (process.env.DD_TRACE_AGENT_URL) {
    tags.pod_name = process.env.HOSTNAME;
  }

  tracer.init({
    ...apmConfig, // Conditionally enable APM tracing & profiling
    runtimeMetrics: true, // Always enable runtime metrics https://docs.datadoghq.com/tracing/metrics/runtime_metrics/nodejs/?tab=environmentvariables
    tags,
  }); // initialized in a different file to avoid hoisting.
}

/**
 * WARNING to projects importing this
 * Even if dd-tracer documents that instrumentation happens at **.init() time**
 * (see https://docs.datadoghq.com/tracing/trace_collection/automatic_instrumentation/dd_libraries/nodejs/#import-and-initialize-the-tracer ),
 *   1. dd-tracer has no choice but to do some stuff **at import time**
 *   2. dd-tracer is not exempt from bugs, like https://github.com/DataDog/dd-trace-js/issues/5211
 *
 * So, do not assume that dd-trace is *fully off* by default! Some of it runs!
 * If you want to entirely disable all of dd-trace (e.g. during unit tests),
 * then you must set `DD_TRACE_ENABLED=false`
 *
 * Q: Why not move the dd-trace import inside the `if DD_TRACE_ENABLED` condition, then?
 * A: Because the future is ESM, and ESM imports must be static and top-level.
 */
export const DD_TRACER = tracer;
