import { createRouter, createWebHistory } from 'vue-router'
import AuthenticatedLayout from '@/components/layouts/AuthenticatedLayout.vue'
import UnauthenticatedLayout from '@/components/layouts/UnauthenticatedLayout.vue'
import HomeView from '@/views/HomeView.vue'
import LandingView from '@/views/LandingView.vue'
import { useAuthStore } from '@/stores/auth'
import { storeToRefs } from 'pinia'
import TestView from '@/views/TestView.vue'
import { InfoService } from '@/services/InfoService'

const info = new InfoService()

const routes = [
  {
    path: '/',
    component: UnauthenticatedLayout,
    children: [
      {
        path: '',
        component: LandingView,
        name: 'landing',
      },
    ],
  },
  {
    props: { navbar: true },
    path: '/home',
    component: AuthenticatedLayout,
    children: [
      {
        path: '',
        name: 'home',
        component: HomeView,
        meta: {
          requiresAuth: true,
        },
      },
    ],
    // route level code-splitting
    // this generates a separate chunk (About.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    // component: () => import('../views/AboutView.vue')
  },
  {
    props: { navbar: true },
    path: '/match/:id',
    component: AuthenticatedLayout,
    children: [
      {
        path: '',
        name: 'match',
        component: () => import('@/views/MatchView.vue'),
        meta: {
          requiresAuth: true,
        },
      },
    ],
  },
  {
    props: { navbar: false },
    path: '/game/:id',
    component: AuthenticatedLayout,
    children: [
      {
        path: '',
        name: 'game',
        component: () => import('@/views/GameView.vue'),
        meta: {
          requiresAuth: true,
        },
      },
    ],
  },
]

if (info.development) {
  routes.push({
    path: '/test',
    component: UnauthenticatedLayout,
    children: [
      {
        path: '',
        component: TestView,
        name: 'test',
      },
    ],
  })
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

router.beforeEach((to, from, next) => {
  const auth = useAuthStore()
  const { user } = storeToRefs(auth)
  const isLoggedIn = user.value === undefined ? false : true
  if (to.name === 'landing' && isLoggedIn) {
    next({ name: 'home' })
  } else if (to.matched.some((record) => record.meta.requiresAuth) && !isLoggedIn) {
    next({ name: 'landing' })
  } else {
    next()
  }
})

export default router
