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

const routes = [
  {
    path: '/',
    redirect: '/ward',
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/LoginView.vue'),
    meta: { title: 'Sign In', public: true },
  },
  {
    path: '/ward',
    name: 'WardDashboard',
    component: () => import('@/views/WardDashboard.vue'),
    meta: { title: 'Virtual Ward', layout: 'default' },
  },
  {
    path: '/patients/:encounterId',
    name: 'PatientDetail',
    component: () => import('@/views/PatientDetail.vue'),
    meta: { title: 'Patient Detail', layout: 'default' },
  },
  {
    path: '/alerts',
    name: 'AlertCenter',
    component: () => import('@/views/AlertCenter.vue'),
    meta: { title: 'Alert Center', layout: 'default' },
  },
  {
    path: '/feedback',
    name: 'FeedbackSummary',
    component: () => import('@/views/FeedbackSummary.vue'),
    meta: { title: 'Feedback Summary', layout: 'default' },
  },
]

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

router.beforeEach((to) => {
  document.title = `${to.meta.title ?? 'VigilCare'} — VigilCare`

  const auth = useAuthStore()
  if (!to.meta.public && !auth.isAuthenticated) {
    return { path: '/login', query: { redirect: to.fullPath } }
  }
  if (to.path === '/login' && auth.isAuthenticated) {
    return { path: '/ward' }
  }
})

export default router
