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

const routes = [
  {
    path: '/',
    name: 'Home',
    redirect: '/sites',
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/pages/Login.vue'),
    meta: { public: true },
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/pages/Register.vue'),
    meta: { public: true },
  },
  {
    path: '/sites',
    name: 'Sites',
    component: () => import('@/pages/Sites.vue'),
  },
  {
    path: '/sites/:siteId',
    name: 'SiteDetail',
    component: () => import('@/pages/SiteDetail.vue'),
    props: true,
  },
  {
    path: '/billing',
    name: 'Billing',
    component: () => import('@/pages/Billing.vue'),
  },
  {
    path: '/billing/invoices',
    name: 'Invoices',
    component: () => import('@/pages/Invoices.vue'),
  },
  {
    path: '/settings',
    name: 'Settings',
    component: () => import('@/pages/Settings.vue'),
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/pages/NotFound.vue'),
    meta: { public: true },
  },
]

const router = createRouter({
  history: createWebHistory('/portal'),
  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
