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

/**
 * Client-side init for non-Next.js (Vite/React) runtimes (TanStack Start).
 * Mirrors init-client.ts but uses @sentry/react directly. R31, R32, R33,
 * R34, R35, R37 still apply.
 */
export function initSentryClientReact(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 SentryReact.init>[0];
  SentryReact.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
    replaysSessionSampleRate: 0.0, // R37
    replaysOnErrorSampleRate: 1.0, // R37
    integrations: [
      // R34, R35 — mandatory mask flags; allowlist starts empty
      SentryReact.replayIntegration({
        maskAllText: true,
        maskAllInputs: true,
        blockAllMedia: true,
      }),
    ],
    initialScope: { tags: { app: opts.app } },
  });
}
