import * as Sentry from "@sentry/nextjs"

const otelEnabled = process.env.NODE_ENV === "production" || process.env.OTEL_ENABLED === "true"

export async function register() {
  if (!otelEnabled) return
  if (process.env.NEXT_RUNTIME !== "nodejs") return

  // Dynamic imports so OTel packages are only loaded when tracing is active
  const { NodeSDK } = await import("@opentelemetry/sdk-node")
  const { getNodeAutoInstrumentations } = await import("@opentelemetry/auto-instrumentations-node")
  const { PrismaInstrumentation } = await import("@prisma/instrumentation")
  const { SentrySpanProcessor, SentryPropagator, SentrySampler } =
    await import("@sentry/opentelemetry")

  const sentryClient = Sentry.getClient()

  const sdk = new NodeSDK({
    sampler: sentryClient ? new SentrySampler(sentryClient) : undefined,
    spanProcessors: [new SentrySpanProcessor()],
    textMapPropagator: new SentryPropagator(),
    instrumentations: [
      getNodeAutoInstrumentations({
        // Disable noisy/low-value instrumentations
        "@opentelemetry/instrumentation-fs": { enabled: false },
        "@opentelemetry/instrumentation-dns": { enabled: false },
        "@opentelemetry/instrumentation-net": { enabled: false },
        // winston-transport is an optional dep — not installed
        "@opentelemetry/instrumentation-winston": { enabled: false },
      }),
      new PrismaInstrumentation(),
    ],
  })

  sdk.start()
}

export const onRequestError = Sentry.captureRequestError
