import { createRouter, createWebHistory } from 'vue-router'
import { currentLang, langs } from './langs'
import { getSettings } from './settings'
import { useAuthStore } from '@/stores/auth'
import { getRoutes } from './menu'

function isAuthenticated(): boolean {
  if (typeof document === 'undefined') return false
  return document.cookie.split('; ').some((c) => c === 'is_authenticated=1')
}
await getSettings()

const routes = await getRoutes()
let newRoutes = []
for (let r of routes) {
  const component = () => import(/* @vite-ignore */ `..${r.component}`)
  newRoutes.push({
    path: r.path,
    component,
    name: r.name,
    meta: r.meta ? JSON.parse(r.meta) : {},
  })
}

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_BASE_URL),
  routes: [
    {
      path: '/',
      redirect: () => `/${currentLang.value?.iso_code}`,
    },
    {
      path: '/:locale',
      name: 'locale',
      children: [
        ...newRoutes,
        {
          path: ':pathMatch(.*)*',
          component: () => import('@/views/NotFoundView.vue'),
          name: 'not-found-child',
        },
      ],
    },
    {
      path: '/:pathMatch(.*)*',
      component: () => import('@/views/NotFoundView.vue'),
      name: 'not-found-root',
    },
  ],
})

router.beforeEach((to, from) => {
  const locale = to.params.locale as string
  const localeLang = langs.find((x) => x.iso_code === locale)

  if (locale && langs.length > 0) {
    const authStore = useAuthStore()
    const validLocale = langs.find((l) => l.lang_code === locale)

    if (validLocale) {
      currentLang.value = localeLang

      if (!to.meta?.guest && !authStore.isAuthenticated) {
        return { name: 'login', params: { locale } }
      }

      return true
    } else if (locale) {
      return `/${currentLang.value?.iso_code}${to.path.replace(`/${locale}`, '') || '/'}`
    }
  }

  if (!locale && to.path !== '/') {
    return `/${currentLang.value?.iso_code}${to.path}`
  }

  return true
})

export default router
