/**
 * OpenTelemetry bootstrap — must be imported before any other app module.
 * main.ts imports this as its first line.
 */
import { NodeSDK } from '@opentelemetry/sdk-node';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { ConsoleSpanExporter } from '@opentelemetry/sdk-trace-node';
import { resourceFromAttributes } from '@opentelemetry/resources';

const exporter = process.env['OTEL_EXPORTER_OTLP_ENDPOINT']
  ? new OTLPTraceExporter()   // reads OTEL_EXPORTER_OTLP_ENDPOINT from env
  : new ConsoleSpanExporter();

const sdk = new NodeSDK({
  resource: resourceFromAttributes({ 'service.name': 'fog-expedition-api' }),
  traceExporter: exporter,
  instrumentations: [
    getNodeAutoInstrumentations({
      // fs instrumentation is too noisy for a server with many module loads.
      '@opentelemetry/instrumentation-fs': { enabled: false },
    }),
  ],
});

sdk.start();

process.on('SIGTERM', () => {
  sdk.shutdown().finally(() => process.exit(0));
});
