// @sentry/cloudflare is lazy-loaded on first captureCaught call.
// Static top-level import blew the Bundled-tier 10ms CPU ceiling at cold-start.
// Dynamic import is cached per-isolate by the JS module system.

import type * as SentryCloudflare from '@sentry/cloudflare';
import { scrubErrorForLog, scrubPii } from './pii-scrub.js';

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

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

let sentryPromise: Promise<typeof SentryCloudflare> | null = null;

function getSentry(): Promise<typeof SentryCloudflare> {
  return (sentryPromise ??= import('@sentry/cloudflare'));
}

export function captureCaught(err: unknown, ctx: CaptureCtx): void {
  const level = ctx.severity ?? 'error';
  if (level === 'error') {
    console.error(`[captureCaught] scope=${ctx.scope}:`, scrubErrorForLog(err));
  }
  const scrubbedExtra = scrubPii(ctx.extra ?? {}) as Record<string, unknown>;
  getSentry()
    .then((Sentry) => {
      Sentry.withScope((scope) => {
        scope.setTag('scope', ctx.scope);
        scope.setLevel(level);
        scope.setExtras(scrubbedExtra);
        const reportErr =
          err instanceof Error
            ? Object.assign(new Error(scrubErrorForLog(err)), { name: err.name })
            : err;
        Sentry.captureException(reportErr);
      });
    })
    .catch((sentryErr) => {
      console.warn('[captureCaught.server] Sentry capture failed:', sentryErr);
    });
}
