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

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

export function initSentryServer(opts: InitServerOpts): 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["VERCEL_ENV"] ??
    process.env["NODE_ENV"] ??
    "development";
  const release = opts.release ?? process.env["VERCEL_GIT_COMMIT_SHA"] ?? "unknown";

  type InitOpts = Parameters<typeof Sentry.init>[0];
  Sentry.init({
    dsn: opts.dsn,
    environment,
    release,
    tracesSampleRate,
    sendDefaultPii: false, // R31 — non-negotiable
    beforeSend: beforeSend as unknown as InitOpts["beforeSend"], // R32
    beforeSendTransaction: beforeSendTransaction as unknown as InitOpts["beforeSendTransaction"], // R33
    initialScope: { tags: { app: opts.app } },
  });
}
