export default defineNuxtRouteMiddleware((to, from) => {
  // important: routes do not exist in middleware, never (in)directly use e.g. useRoute

  if (!import.meta.client) return

  if (to.matched.length) {
    const config = useContentConfig()
    const { preferredLocale, preferredVariant } = useContentPreference()

    const locales = config.locale?.list.map((l) => l.code) ?? []
    if (to.params.locale !== undefined && !locales.includes(to.params.locale)) {
      return navigateTo(
        '/' + preferredLocale.value + to.fullPath.slice(to.params.locale.length + 1)
      )
    }

    const variants = config.variant?.list.map((v) => v.code) ?? []
    if (to.params.variant !== undefined && !variants.includes(to.params.variant)) {
      const prefix = to.params.locale === undefined ? '/' : '/' + to.params.locale + '/'
      return navigateTo(
        prefix +
          preferredVariant.value +
          to.fullPath.slice(prefix.length + to.params.variant.length)
      )
    }
  } else {
    const { preferredLocale, preferredVariant } = useContentPreference()
    return navigateTo(
      '/' + [preferredLocale.value, preferredVariant.value].filter((p) => !!p).join('/')
    )
  }
})
