type RestErrorLike = {
	code?: string
	message?: string
	data?: { status?: number }
}

const isBenignGuestRestError = (reason: unknown): boolean => {
	if (!reason || typeof reason !== 'object') {
		return false
	}

	const error = reason as RestErrorLike

	if (error.code === 'rest_not_logged_in') {
		return true
	}

	if (error.data?.status === 401) {
		return true
	}

	if (typeof error.message === 'string' && error.message.includes('not currently logged in')) {
		return true
	}

	return false
}

/**
 * Prevent guest /users/me 401 rejections from becoming unhandled during WC block
 * checkout hydration (see WooCommerce #64474).
 */
export const installHydrationGuard = (): void => {
	if (typeof window === 'undefined') {
		return
	}

	const globalWindow = window as Window & { __greenpayHydrationGuardInstalled?: boolean }
	if (globalWindow.__greenpayHydrationGuardInstalled) {
		return
	}

	globalWindow.__greenpayHydrationGuardInstalled = true

	window.addEventListener('unhandledrejection', (event) => {
		if (isBenignGuestRestError(event.reason)) {
			event.preventDefault()
		}
	})
}

installHydrationGuard()
