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

/**
 * Server-side init for non-Next.js runtimes (TanStack Start). Mirrors
 * init-server.ts but uses @sentry/node directly. R31, R32, R33 still apply.
 */
export function initSentryServerNode(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["VITE_GIT_COMMIT_SHA"] ?? "unknown";

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