import { createRouter, createWebHistory } from 'vue-router'
import HomePage from '@/views/HomePage.vue'
import AboutPage from '@/views/AboutPage.vue'
import LoginPage from '@/views/LoginPage.vue'
import MediaPage from '@/views/MediaPage.vue'
import ElementPage from '@/views/ElementPage.vue'
import AdminElementPage from '@/views/AdminElementPage.vue'
import { useAuthStore } from '@/stores/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomePage,
    },
    {
      path: '/login',
      name: 'login',
      component: LoginPage,
    },
    {
      path: '/about',
      name: 'about',
      component: AboutPage,
    },
    {
      path: '/contact',
      redirect: { name: 'home' },
    },
    {
      path: '/media',
      name: 'media',
      component: MediaPage,
    },
    {
      path: '/element/:id',
      name: 'element',
      component: ElementPage,
    },
    {
      path: '/admin/element/:id',
      name: 'admin-element',
      component: AdminElementPage,
    },
  ],
})

router.beforeEach(async (to) => {
  if (to.name !== 'admin-element') {
    return true
  }

  const authStore = useAuthStore()
  if (!authStore.isAuthenticated) {
    await authStore.fetchUser()
  }

  if (!authStore.isAuthenticated) {
    return { name: 'login' }
  }

  return true
})

export default router
