import * as Sentry from '@sentry/nuxt'

export default function errorHandlingHelper(err: any, error: any) {
  // Only use the original error's status code - never fall through to the retry/refresh error's status.
  // When the refresh attempt fails with 401, that 401 should NOT become the response status
  // (it would incorrectly trigger forceLogoutHelper even when the original error was a 500).
  const status = err?.status?.status ?? err?.status ?? err?.statusCode ?? 500
  const message = err?.status?.detail ?? err?.detail ?? err?.message ?? err?.statusMessage ?? error?.detail ?? error?.message ?? error?.statusMessage ?? ''

  // Report only genuine server failures to Sentry. The standard route pattern catches and
  // RETURNS errors (never re-throws), so Sentry's automatic Nitro capture never sees them —
  // this single funnel covers all ~1177 routes. 401/403/404 are expected auth/permission/
  // empty flows (already handled by refresh + forceLogout), so skip them to avoid noise.
  // Telemetry must NEVER affect the API response → fully guarded.
  if (process.env.SENTRY_DSN && Number(status) >= 500) {
    try {
      const captured = err instanceof Error
        ? err
        : new Error(typeof message === 'string' && message ? message : JSON.stringify(message ?? err))
      Sentry.captureException(captured, {
        level: 'error',
        tags: { source: 'errorHandlingHelper', status: String(status) },
        extra: { originalError: err, refreshError: error },
      })
    } catch { /* swallow — never let monitoring break the response */ }
  }

  return { status, message }
}
