/**
 * Universal caught-error sink.
 *
 * Uses the static @sentry/astro import for both server and browser.
 * The dynamic import was removed: vite-plugin-top-level-await wraps
 * __vite__preload for any module with a dynamic import, generating a
 * __tla export that propagates up the static-import chain into island
 * bundles — causing Astro's island runtime to read Component === undefined.
 * @sentry/astro is already bundled in the client chunk via the static
 * import, so removing lazy-loading has zero bundle-size impact.
 *
 * Never throws. Returns void.
 */

import * as Sentry from '@sentry/astro';
import { scrubPii } from '@/server/observability/pii-scrub.js';

type Severity = 'error' | 'warning' | 'info';

export interface CaptureCtx {
  scope: string;
  severity?: Severity;
  extra?: Record<string, unknown>;
}

export function captureCaught(err: unknown, ctx: CaptureCtx): void {
  const level = ctx.severity ?? 'error';
  const extras = scrubPii(ctx.extra ?? {}) as Record<string, unknown>;

  try {
    Sentry.withScope((scope) => {
      scope.setTag('scope', ctx.scope);
      scope.setLevel(level);
      scope.setExtras(extras);
      Sentry.captureException(err);
    });
  } catch (sentryErr) {
    console.warn('[captureCaught] Sentry capture failed:', sentryErr);
  }
}
