import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/authStore.js'

import LoginPage from '../views/LoginPage.vue'
import RegisterPage from '../views/RegisterPage.vue'
import LandingPage from '../views/LandingPage.vue'
import LibraryPage from '../views/LibraryPage.vue'
import PlaylistPage from '../views/PlaylistPage.vue'
import PlaylistDetail from '../views/PlaylistDetail.vue'
import ProfilePage from '../views/ProfilePage.vue'
import AdminPage from '../views/AdminPage.vue'

const routes = [
  { path: '/', redirect: '/home' },
  { path: '/login', name: 'Login', component: LoginPage, meta: { guest: true } },
  { path: '/register', name: 'Register', component: RegisterPage, meta: { guest: true } },
  { path: '/home', name: 'Home', component: LandingPage },
  { path: '/library', name: 'Library', component: LibraryPage },
  { path: '/playlist', name: 'Playlist', component: PlaylistPage },
  { path: '/playlist/:id', name: 'PlaylistDetail', component: PlaylistDetail },
  { path: '/profile', name: 'Profile', component: ProfilePage },
  { path: '/admin/tracks', name: 'AdminTracks', component: AdminPage, meta: { admin: true } },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()

  if (to.meta.admin && !authStore.isAdmin) {
    return next('/home')
  }

  if (to.meta.guest && authStore.isLoggedIn) {
    return next('/home')
  }

  next()
})

export default router
