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

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/LoginView.vue'),
    meta: { guest: true },
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/RegisterView.vue'),
    meta: { guest: true },
  },
  {
    path: '/',
    component: () => import('../views/AppLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        redirect: '/files',
      },
      {
        path: 'files/:folderId?',
        name: 'Files',
        component: () => import('../views/FilesView.vue'),
      },
      {
        path: 'preview/:fileId',
        name: 'Preview',
        component: () => import('../views/PreviewView.vue'),
      },
      {
        path: 'trash',
        name: 'Trash',
        component: () => import('../views/TrashView.vue'),
      },
      {
        path: 'calendar',
        name: 'Calendar',
        component: () => import('../views/CalendarView.vue'),
      },
      {
        path: 'contacts',
        name: 'Contacts',
        component: () => import('../views/ContactsView.vue'),
      },
      {
        path: 'email',
        name: 'Email',
        component: () => import('../views/EmailView.vue'),
      },
      {
        path: 'passwords',
        name: 'Passwords',
        component: () => import('../views/PasswordsView.vue'),
      },
      {
        path: 'admin',
        name: 'Admin',
        component: () => import('../views/AdminView.vue'),
        meta: { requiresAdmin: true },
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('../views/SettingsView.vue'),
      },
    ],
  },
  {
    path: '/clients',
    name: 'Clients',
    component: () => import('../views/ClientsView.vue'),
  },
  {
    path: '/share/:token',
    name: 'Share',
    component: () => import('../views/ShareView.vue'),
  },
]

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

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

  if (to.meta.requiresAuth && !auth.isAuthenticated) {
    // Try to refresh token
    try {
      await auth.refreshToken()
      await auth.fetchMe()
    } catch {
      return next('/login')
    }
  }

  if (to.meta.guest && auth.isAuthenticated) {
    return next('/')
  }

  if (to.meta.requiresAdmin && !auth.isAdmin) {
    return next('/')
  }

  next()
})

export default router
