import { createRouter as _createRouter, createWebHistory } from 'vue-router'

import HomeView from '../views/HomeView.vue'
import TopicHubView from '../views/TopicHubView.vue'
import TierEditorView from '../views/TierEditorView.vue'
import LoginView from '../views/LoginView.vue'
import MyTierListsView from '../views/MyTierListsView.vue'
import FavoriteTierListsView from '../views/FavoriteTierListsView.vue'
import FollowingFeedView from '../views/FollowingFeedView.vue'
import UserProfileView from '../views/UserProfileView.vue'
import AdminView from '../views/AdminView.vue'
import ProfileView from '../views/ProfileView.vue'
import SearchResultsView from '../views/SearchResultsView.vue'
import { useAuthStore } from '../stores/auth'

export function createRouter() {
  const router = _createRouter({
    history: createWebHistory(),
    routes: [
      { path: '/', name: 'home', component: HomeView },
      { path: '/topics/:topicId', name: 'topicHub', component: TopicHubView },
      { path: '/editor/:topicId/new', name: 'newEditor', component: TierEditorView },
      { path: '/editor/:topicId/:tierListId', name: 'editEditor', component: TierEditorView },
      { path: '/login', name: 'login', component: LoginView },
      { path: '/me', name: 'me', component: MyTierListsView },
      { path: '/favorites', name: 'favorites', component: FavoriteTierListsView },
      { path: '/following', name: 'followingFeed', component: FollowingFeedView },
      { path: '/search', name: 'search', component: SearchResultsView },
      { path: '/admin', redirect: '/admin/featured' },
      { path: '/admin/featured', name: 'adminFeatured', component: AdminView },
      { path: '/admin/templates', name: 'adminTemplates', component: AdminView },
      { path: '/admin/items', name: 'adminItems', component: AdminView },
      { path: '/admin/tierlists', name: 'adminTierlists', component: AdminView },
      { path: '/admin/users', name: 'adminUsers', component: AdminView },
      { path: '/profile', name: 'profile', component: ProfileView },
      { path: '/users/:userId', name: 'userProfile', component: UserProfileView },
    ],
  })

  router.beforeEach(async (to) => {
    const routeName = String(to.name || '')
    if (!routeName.startsWith('admin')) return true

    const auth = useAuthStore()
    if (!auth.hydrated) await auth.refresh()
    if (!auth.user?.isAdmin) {
      return { path: '/' }
    }
    return true
  })

  return router
}
