/**
 * Transient DO error classifier.
 *
 * CF runtime errors that are infrastructure hiccups (storage timeout, DO reset,
 * network loss) should be logged for audit but NOT trigger Sentry notifications.
 * Use severity:'warning' for these — they are recorded but don't page.
 */

import { captureCaught, type CaptureCtx } from './capture.server.js';

const TRANSIENT_PATTERNS = [
  /storage operation exceeded timeout/i,
  /Durable Object.*reset/i,
  /Network connection lost/i,
  /exceeded (the )?CPU time limit/i,
  /The Durable Object's code was updated/i,
  /Durable Object storage is currently unavailable/i,
  /internal error/i, // CF generic transient
] as const;

/**
 * Returns true if the error matches a known transient CF runtime error pattern.
 * These are infrastructure hiccups, not application bugs.
 */
export function isTransientDoError(err: unknown): boolean {
  if (err == null) return false;
  const message = err instanceof Error ? err.message : typeof err === 'string' ? err : String(err);
  return TRANSIENT_PATTERNS.some((pattern) => pattern.test(message));
}

/**
 * Capture a transient error at warning severity.
 * Captured in Sentry (searchable) without notification.
 */
export function captureTransient(err: unknown, ctx: Omit<CaptureCtx, 'severity'>): void {
  captureCaught(err, { ...ctx, severity: 'warning' });
}
