import HomePage from '@/pages/home/HomePage.vue'
import LoginPage from '@/pages/login/LoginPage.vue'
import LaravelPage from '@/pages/testing/LaravelPage.vue'
import WebsocketsPage from '@/pages/testing/WebsocketsPage.vue'
import UserPage from '@/pages/user/UserPage.vue'
import { createRouter, createWebHistory } from 'vue-router'
import TestAnimations from '@/pages/TestAnimations.vue'
import TestDealing from '@/pages/TestDealing.vue'
import TestAllAnimations from '@/pages/TestAllAnimations.vue'
import TestGameBoard from '@/pages/TestGameBoard.vue'
import SinglePlayerGamePage from '@/pages/game/SinglePlayerGamePage.vue'
import RegisterPage from '@/pages/register/RegisterPage.vue'
import CoinsPurchasePage from '@/pages/purchase/CoinPurchasePage.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomePage,
    },
    {
      path: '/login',
      name: 'login',
      component: LoginPage,
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterPage,
    },
    {
      path: '/game/3',
      name: 'bisca3',
      component: SinglePlayerGamePage,
      props: { gameType: 3 },
      meta: { requiresAuth: true },
    },
    {
      path: '/game/9',
      name: 'bisca9',
      component: SinglePlayerGamePage,
      props: { gameType: 9 },
      meta: { requiresAuth: true },
    },
    {
      path: '/user',
      component: UserPage,
      meta: { requiresAuth: true },
    },
    {
      path: '/coins-purchase',
      component: CoinsPurchasePage,
      meta: { requiresAuth: true },
    },
    {
      path: '/testing',
      children: [
        {
          path: 'laravel',
          component: LaravelPage,
        },
        {
          path: 'websockets',
          component: WebsocketsPage,
        },
        {
          path: 'animations',
          component: TestAnimations,
        },
        {
          path: 'dealing',
          component: TestDealing,
        },
        {
          path: 'all-animations',
          component: TestAllAnimations,
        },
        {
          path: 'gameboard',
          component: TestGameBoard,
        },
      ],
    },
  ],
})

router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some((record) => record.meta.requiresAuth)

  if (requiresAuth) {
    const token = localStorage.getItem('token')

    if (!token) {
      return next({ name: 'login' })
    }
  }
  next()
})

export default router
