import { createRouter, createWebHistory } from 'vue-router'
import HomeView from './views/HomeView.vue'

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('./views/LoginView.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: true }
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('./views/SearchView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/persons',
    name: 'persons',
    component: () => import('./views/PersonsView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/faces/candidates',
    name: 'face-candidates',
    component: () => import('./views/FaceCandidatesView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/files',
    name: 'files',
    component: () => import('./views/FilesView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/settings',
    name: 'settings',
    component: () => import('./views/SettingsView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/videos/:uuid',
    name: 'video-detail',
    component: () => import('./views/VideoDetailView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/chunk-detail/:uuid/:chunkId',
    name: 'chunk-detail',
    component: () => import('./views/ChunkDetailView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/identity/:id',
    name: 'identity-detail',
    component: () => import('./views/IdentityDetailView.vue'),
    meta: { requiresAuth: true }
  }
]

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

router.beforeEach((to, _from, next) => {
  const user = localStorage.getItem('momentry_user')
  
  // If route requires auth and user is not logged in, redirect to login
  if (to.meta.requiresAuth !== false && !user) {
    next('/login')
  } 
  // If user is logged in and trying to access login, redirect to home
  else if (to.path === '/login' && user) {
    next('/home')
  } else {
    next()
  }
})

export default router
