// This file configures the initialization of Sentry on the server.
// The config you add here will be used whenever the server handles a request.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/
import * as Sentry from "@sentry/nextjs";
import { logger } from "@formbricks/logger";
import { SENTRY_DSN, SENTRY_ENVIRONMENT, SENTRY_RELEASE } from "@/lib/constants";
import { isScannerMultipartNoise } from "@/lib/sentry/scanner-noise";
import { scrubWebhookTokens } from "@/lib/sentry/scrub-webhook-tokens";

if (SENTRY_DSN) {
  logger.info("Sentry DSN found, enabling Sentry on the server");

  Sentry.init({
    dsn: SENTRY_DSN,
    release: SENTRY_RELEASE,
    environment: SENTRY_ENVIRONMENT,

    // No tracing while Sentry doesn't update to telemetry 2.0.0 - https://github.com/getsentry/sentry-javascript/issues/15737
    tracesSampleRate: 0,

    // Keep Sentry from registering its own TracerProvider; app telemetry is handled by instrumentation-node.ts
    skipOpenTelemetrySetup: true,

    // Setting this option to true will print useful information to the console while you're setting up Sentry.
    debug: false,

    // Disable telemetry and additional data collection
    sendDefaultPii: false,
    sendClientReports: false,

    // uncomment the line below to enable Spotlight (https://spotlightjs.com)
    // spotlight: process.env.NODE_ENV === 'development',

    beforeSend(event, hint) {
      const error = hint.originalException as Error;

      // @ts-expect-error -- Next.js adds `digest` to the errors it throws; `Error` does not declare it
      if (error?.digest === "NEXT_NOT_FOUND") {
        return null;
      }

      // Scanner traffic, not ours: a malformed multipart body that undici rejects before any handler
      // sees it. Scoped on the stack rather than the route -- see `isScannerMultipartNoise`.
      if (isScannerMultipartNoise(event)) {
        return null;
      }

      // A Webhook Secret URL's token is a credential (ADR 0057); it never leaves in an event.
      return scrubWebhookTokens(event);
    },

    beforeSendTransaction(event) {
      return scrubWebhookTokens(event);
    },
  });
} else {
  logger.warn("Sentry DSN not found, Sentry will be disabled on the server");
}
