// packages/core-shared/src/instrumentation/sentry/init-client.ts
import * as Sentry from "@sentry/nextjs";
import { beforeSend, beforeSendTransaction } from "./scrub";

export type InitClientOpts = {
  dsn: string | undefined;
  app: "web-next" | "cms" | "web-tanstack";
  release?: string;
};

export function initSentryClient(opts: InitClientOpts): void {
  if (!opts.dsn) return;

  const isProd = process.env["NODE_ENV"] === "production";
  const tracesSampleRate =
    process.env["SENTRY_TRACES_SAMPLE_RATE"] !== undefined
      ? Number(process.env["SENTRY_TRACES_SAMPLE_RATE"])
      : isProd
        ? 0.1
        : 1.0;

  const environment =
    process.env["SENTRY_ENVIRONMENT"] ?? process.env["NODE_ENV"] ?? "development";
  const release = opts.release ?? "unknown";

  type InitOpts = Parameters<typeof Sentry.init>[0];
  Sentry.init({
    dsn: opts.dsn,
    environment,
    release,
    tracesSampleRate,
    sendDefaultPii: false, // R31
    beforeSend: beforeSend as unknown as InitOpts["beforeSend"], // R32
    beforeSendTransaction: beforeSendTransaction as unknown as InitOpts["beforeSendTransaction"], // R33
    replaysSessionSampleRate: 0.0, // R37 — privacy default
    replaysOnErrorSampleRate: 1.0, // R37
    integrations: [
      // R34, R35 — mandatory mask flags; allowlist starts empty
      Sentry.replayIntegration({
        maskAllText: true,
        maskAllInputs: true,
        blockAllMedia: true,
      }),
    ],
    initialScope: { tags: { app: opts.app } },
  });
}
