import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/LoginView.vue'
import RegisterView from '../views/RegisterView.vue'
import { useAuthStore } from '@/stores/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterView
    },
    {
      path: '/admin/approvals',
      name: 'approvals',
      component: () => import('../views/UserApprovalView.vue'),
      meta: { requiresAdmin: true }
    },
    {
      path: '/',
      name: 'home',
      component: () => import('../views/FlexibleGenerationView.vue')
    },
    {
      path: '/characters',
      name: 'characters',
      component: () => import('../views/CharactersView.vue')
    },
    {
      path: '/assets',
      name: 'assets',
      component: () => import('../views/AssetsView.vue')
    },
    {
      path: '/characters/:id',
      name: 'character-detail',
      component: () => import('../views/CharacterDetailView.vue')
    },
    {
      path: '/image-to-prompt',
      name: 'image-to-prompt',
      component: () => import('../views/ImageToPromptView.vue')
    },
    {
      path: '/generation',
      name: 'generation',
      component: () => import('../views/ImageGenerationView.vue')
    },
    {
      path: '/flexible',
      name: 'flexible',
      component: () => import('../views/FlexibleGenerationView.vue')
    },
    {
      path: '/albums',
      name: 'albums',
      component: () => import('../views/AlbumsView.vue')
    },
    {
      path: '/projects',
      name: 'projects',
      component: () => import('../views/ProjectsView.vue')
    },
    {
      path: '/projects/:id',
      name: 'project-detail',
      component: () => import('../views/ProjectDetailView.vue')
    },
    {
      path: '/albums/:id',
      name: 'album-detail',
      component: () => import('../views/AlbumDetailView.vue')
    }
  ]
})

router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  const publicPages = ['/login', '/register']
  const authRequired = !publicPages.includes(to.path)
  
  if (authRequired) {
    if (!authStore.isAuthenticated) {
      return next('/login')
    }
    
    // Check if route requires admin
    if (to.meta.requiresAdmin && !authStore.isAdmin()) {
      return next('/') // Redirect non-admins to home
    }
  } else if ((to.name === 'login' || to.name === 'register') && authStore.isAuthenticated) {
    return next('/')
  }
  
  next()
})

export default router
