import { ApiError } from '../api/client'

/**
 * Dev-only safety net for unhandled promise rejections.
 *
 * Call sites should still handle their own errors (useApi error UI, try/catch
 * around mutations). This guard exists so that any STRAY rejection — typically
 * an ApiError from an endpoint that hasn't shipped yet — is logged with its
 * failing path instead of spamming the console with "Uncaught (in promise)".
 * It surfaces regressions (which endpoint, which status) without turning the
 * page into a dead end. No-op in production builds.
 */
export function installUnhandledRejectionGuard(): void {
  if (!import.meta.env.DEV) return
  window.addEventListener('unhandledrejection', (event) => {
    const reason = event.reason
    if (reason instanceof ApiError) {
      const where = reason.path ? ` [${reason.path}]` : ''
      console.warn(`[API] Unbehandelte Ablehnung${where} (${reason.status ?? 'Netzwerk'}): ${reason.message}`)
      event.preventDefault()
    } else {
      console.warn('[Unbehandelte Promise-Ablehnung]', reason)
    }
  })
}
