/**
 * Next.js instrumentation hook — loads Sentry (Glitchtip) init on server/edge.
 *
 * https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation
 */
export async function register() {
  if (process.env.NEXT_RUNTIME === "nodejs") {
    await import("./sentry.server.config");
  }
  if (process.env.NEXT_RUNTIME === "edge") {
    // Edge runtime gets a slimmer init via the same DSN; the SDK auto-detects.
    await import("./sentry.server.config");
  }
}

// Capture unhandled promise rejections in Server Components / API routes and
// forward them through Sentry's hook. Loaded only on the server.
// Forward unhandled errors from Server Components / Route Handlers to Sentry.
// Loose typing so it tracks any captureRequestError signature change in
// @sentry/nextjs — observability code must not block real errors.
export const onRequestError = async (
  err: unknown,
  request: Parameters<typeof import("@sentry/nextjs").captureRequestError>[1],
  context: Parameters<typeof import("@sentry/nextjs").captureRequestError>[2],
) => {
  if (process.env.NEXT_RUNTIME !== "nodejs") return;
  try {
    const { captureRequestError } = await import("@sentry/nextjs");
    await captureRequestError(err, request, context);
  } catch {
    /* never let observability swallow the original error */
  }
};
