/**
 * Next.js server-side instrumentation entry point.
 *
 * Runs once per server runtime (Node.js or Edge). We branch on
 * NEXT_RUNTIME because Sentry exposes different SDK surfaces for
 * each — Node gets the full node SDK, Edge gets a slimmer one.
 *
 * Required hook for Sentry's Next.js integration to capture
 * server-side exceptions and route handler errors. See
 * https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation
 */

import * as Sentry from '@sentry/nextjs';

export async function register() {
  if (process.env.NEXT_RUNTIME === 'nodejs') {
    Sentry.init({
      dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
      // Adjust later when traffic ramps; 100% sampling is fine for a
      // pre-launch beta with low volume.
      tracesSampleRate: 1.0,
      // Don't send events when DSN is missing (e.g. local dev without
      // Sentry env). Prevents the SDK from logging warnings to stdout.
      enabled: Boolean(process.env.NEXT_PUBLIC_SENTRY_DSN),
      environment: process.env.SENTRY_ENVIRONMENT || process.env.NODE_ENV,
    });
  }

  if (process.env.NEXT_RUNTIME === 'edge') {
    Sentry.init({
      dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
      tracesSampleRate: 1.0,
      enabled: Boolean(process.env.NEXT_PUBLIC_SENTRY_DSN),
      environment: process.env.SENTRY_ENVIRONMENT || process.env.NODE_ENV,
    });
  }
}

// Required for nested React Server Component errors to reach Sentry.
// See https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/#errors-from-nested-react-server-components
export const onRequestError = Sentry.captureRequestError;
