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

const routes = [
  {
    path: '/',
    name: 'Home',
    redirect: '/dashboard',
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/pages/admin/Login.vue'),
    meta: { public: true },
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/pages/admin/Dashboard.vue'),
  },
  {
    path: '/sites',
    name: 'Sites',
    component: () => import('@/pages/admin/Sites.vue'),
  },
  {
    path: '/sites/:siteId',
    name: 'SiteDetail',
    component: () => import('@/pages/admin/SiteDetail.vue'),
    props: true,
  },
  {
    path: '/apps',
    name: 'Apps',
    component: () => import('@/pages/admin/Apps.vue'),
  },
  {
    path: '/apps/:appId',
    name: 'AppDetail',
    component: () => import('@/pages/admin/AppDetail.vue'),
    props: true,
  },
  {
    path: '/servers',
    name: 'Servers',
    component: () => import('@/pages/admin/Servers.vue'),
  },
  {
    path: '/payments',
    name: 'Payments',
    component: () => import('@/pages/admin/Payments.vue'),
  },
  {
    path: '/payments/customers',
    name: 'Customers',
    component: () => import('@/pages/admin/Customers.vue'),
  },
  {
    path: '/logs',
    name: 'Logs',
    component: () => import('@/pages/admin/Logs.vue'),
  },
  {
    path: '/settings',
    name: 'Settings',
    component: () => import('@/pages/admin/Settings.vue'),
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/pages/admin/NotFound.vue'),
    meta: { public: true },
  },
]

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

// Navigation guard - check authentication
router.beforeEach(async (to, from, next) => {
  // Public routes don't need auth
  if (to.meta.public) {
    next()
    return
  }

  // Check if user is logged in
  try {
    await session.init()

    if (session.isLoggedIn) {
      next()
    } else {
      // Save intended destination for redirect after login
      next({ name: 'Login', query: { redirect: to.fullPath } })
    }
  } catch (error) {
    next({ name: 'Login', query: { redirect: to.fullPath } })
  }
})

export default router
