import type { Router } from 'vue-router'

const RELOAD_STORAGE_KEY = 'app:chunk-load-reload'
const RELOAD_INTERVAL = 30 * 1000

const chunkLoadErrorPatterns = [
  'Failed to fetch dynamically imported module',
  'Importing a module script failed',
  'Loading CSS chunk',
  'Unable to preload CSS',
  'ChunkLoadError',
  'CSS_CHUNK_LOAD_FAILED'
]

const getErrorMessage = (error: unknown): string => {
  if (typeof error === 'string') return error
  if (error instanceof Error) return error.message

  const maybeError = error as { message?: unknown; reason?: unknown }
  if (typeof maybeError?.message === 'string') return maybeError.message
  if (typeof maybeError?.reason === 'string') return maybeError.reason
  if (maybeError?.reason instanceof Error) return maybeError.reason.message

  return ''
}

const isChunkLoadError = (error: unknown): boolean => {
  const message = getErrorMessage(error)
  return chunkLoadErrorPatterns.some((pattern) => message.includes(pattern))
}

const reloadPageOnce = () => {
  const now = Date.now()
  const lastReloadAt = Number(sessionStorage.getItem(RELOAD_STORAGE_KEY) || 0)

  if (now - lastReloadAt < RELOAD_INTERVAL) return

  sessionStorage.setItem(RELOAD_STORAGE_KEY, String(now))
  console.log('222', 222)
  window.location.reload()
}

export const setupReloadOnChunkError = (router: Router) => {
  window.addEventListener('vite:preloadError', (event) => {
    event.preventDefault()
    reloadPageOnce()
  })

  router.onError((error) => {
    if (isChunkLoadError(error)) {
      reloadPageOnce()
    }
  })
}
