import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/views/Home.vue'
import Seasons from '@/views/Seasons.vue'
import Teams from '@/views/Teams.vue'
import Drivers from '@/views/Drivers.vue'
import SeasonDetail from '@/views/SeasonDetail.vue'
import DriverDetail from '@/views/DriverDetail.vue'
import TeamDetail from '@/views/TeamDetail.vue'
import Result from '@/views/Result.vue'
import RacePage from '@/views/RacePage.vue'
import RaceResult from '@/views/RaceResult.vue'
import Login from '@/views/Login.vue'
import Register from '@/views/Register.vue'
import CommentDetail from '@/views/CommentDetail.vue'
import { isAuthenticated } from '@/utils/auth'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home,
    },
    {
      path: '/login',
      name: 'login',
      component: Login,
    },
    {
      path: '/register',
      name: 'register',
      component: Register,
    },
    {
      path: '/seasons',
      name: 'seasons',
      component: Seasons,
    },
    {
      path: '/seasons/:year',
      name: 'season-detail',
      component: SeasonDetail,
    },
    {
      path: '/seasons/:year/races/:id',
      name: 'race-page',
      component: RacePage,
    },
    {
      path: '/seasons/:year/races/:id/:type',
      name: 'race-result',
      component: RaceResult,
    },
    {
      path: '/teams',
      name: 'teams',
      component: Teams,
    },
    {
      path: '/teams/:id',
      name: 'team-detail',
      component: TeamDetail,
    },
    {
      path: '/drivers',
      name: 'drivers',
      component: Drivers,
    },
    {
      path: '/drivers/:id',
      name: 'driver-detail',
      component: DriverDetail,
    },
    {
      path: '/drivers/:id/results',
      name: 'driver-result',
      component: Result,
    },
    {
      path: '/teams/:id/results',
      name: 'team-result',
      component: Result,
    }
    ,
    {
      path: '/comments/:id',
      name: 'comment-detail',
      component: CommentDetail,
    }
  ],
})

router.beforeEach((to, from, next) => {
  if (to.name === 'login' || to.name === 'register') {
    next()
    return
  }
  if (!isAuthenticated()) {
    next({ name: 'login' })
  } else {
    next()
  }
})

export default router
