import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/auth.js'
import FileManagerView from '../views/FileManagerView.vue'
import TopicsView from '../views/TopicsView.vue'
import DocumentView from '../views/DocumentView.vue'
import SettingsView from '../views/SettingsView.vue'
import CloudFolderView from '../views/CloudFolderView.vue'
import CloudStorageView from '../views/CloudStorageView.vue'

const routes = [
  // File manager is the home — handles both root and folder views
  { path: '/', component: FileManagerView },
  { path: '/topics', component: TopicsView },
  { path: '/topics/:name', component: TopicsView },
  { path: '/document/:id', component: DocumentView },
  { path: '/settings', component: SettingsView },

  // Phase 2 — public auth routes (no guard)
  {
    path: '/login',
    component: () => import('../views/auth/LoginView.vue'),
    meta: { public: true, layout: 'auth' },
  },
  {
    path: '/register',
    component: () => import('../views/auth/RegisterView.vue'),
    meta: { public: true, layout: 'auth' },
  },
  {
    path: '/password-reset',
    component: () => import('../views/auth/PasswordResetView.vue'),
    meta: { public: true, layout: 'auth' },
  },
  {
    path: '/password-reset/confirm',
    component: () => import('../views/auth/NewPasswordView.vue'),
    meta: { public: true, layout: 'auth' },
  },

  // Phase 2 — authenticated routes
  { path: '/account', redirect: '/settings' },
  { path: '/admin', component: () => import('../views/AdminView.vue'), meta: { requiresAdmin: true } },

  // Cloud storage overview and folder browser
  {
    path: '/cloud',
    name: 'cloud',
    component: CloudStorageView,
    meta: { requiresAuth: true },
  },
  {
    path: '/cloud/:provider/:folderId(.*)',
    name: 'cloud-folder',
    component: CloudFolderView,
    meta: { requiresAuth: true },
  },

  // Phase 4 — folder and sharing routes
  {
    path: '/folders/:folderId',
    name: 'folder',
    component: FileManagerView,
    meta: { requiresAuth: true },
  },
  {
    path: '/shared',
    name: 'shared',
    component: () => import('../views/SharedView.vue'),
    meta: { requiresAuth: true },
  },
]

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

// Navigation guard (D-10): redirect unauthenticated users to /login.
// On page reload the access token is gone (memory-only per CLAUDE.md), so we attempt
// a silent refresh via the httpOnly cookie before concluding the session is gone.
router.beforeEach(async (to) => {
  const authStore = useAuthStore()
  if (!to.meta.public && !authStore.accessToken) {
    try {
      await authStore.refresh()
    } catch {
      return { path: '/login', query: { redirect: to.fullPath } }
    }
  }

  if (to.meta.requiresAdmin && authStore.user?.role !== 'admin') {
    return { path: '/' }
  }
})

export default router
