// Centralized error handling — two utilities for two contexts
//
// handleError:      user-facing errors → classify, log, toast
// handleInfraError: infrastructure errors → log only, never toast

import { extractErrorMessage } from './extract-error-message';
import { classifyError, type ClassifiedError } from './error-classifier';
import { notify } from '../stores/notifications.svelte';
import { tel } from '../adapters/telemetry-bridge';

/** User-facing error handler. Logs to telemetry AND shows a toast. */
export function handleError(
  err: unknown,
  context: string,
  userIntent?: string,
): ClassifiedError {
  const msg = extractErrorMessage(err);
  const classified = classifyError(msg);

  tel.error(context, { error: msg, type: classified.type, retryable: classified.retryable });

  const userMsg = userIntent
    ? `Couldn't ${userIntent}. ${classified.message}`
    : classified.message;

  notify('error', userMsg);

  return classified;
}

/** Infrastructure-only error handler. Logs to telemetry, NEVER toasts.
 *  Use for: telemetry-bridge, notifications-bridge, heartbeats, fire-and-forget persistence. */
export function handleInfraError(err: unknown, context: string): void {
  const msg = extractErrorMessage(err);
  tel.error(`[infra] ${context}`, { error: msg });
}

/** Convenience: user-facing warning (toast + log, no classification). */
export function handleWarning(message: string, context: string): void {
  tel.warn(context, { message });
  notify('warning', message);
}
