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

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/LoginView.vue'),
    meta: { requiresAuth: false },
  },
  {
    path: '/',
    component: () => import('../layouts/AuthenticatedLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        redirect: () => {
          const auth = useAuthStore()
          return auth.isAuthenticated
            ? getDefaultRouteForRole(auth.userRole)
            : '/login'
        },
      },
      {
        path: 'intake',
        name: 'Intake',
        component: () => import('../views/IntakeView.vue'),
        meta: { requiresAuth: true, roles: ['INTAKE_CLERK', 'ADMINISTRATOR'] },
      },
      {
        path: 'cover-sheets',
        name: 'CoverSheets',
        component: () => import('../views/CoverSheetView.vue'),
        meta: { requiresAuth: true, roles: ['INTAKE_CLERK', 'ADMINISTRATOR'] },
      },
      {
        path: 'entry',
        name: 'EntryQueue',
        component: () => import('../views/EntryView.vue'),
        meta: { requiresAuth: true, roles: ['DATA_ENTRY_CLERK', 'ADMINISTRATOR'] },
      },
      {
        path: 'entry/:batchId',
        name: 'EntryBatch',
        component: () => import('../views/EntryView.vue'),
        meta: { requiresAuth: true, roles: ['DATA_ENTRY_CLERK', 'ADMINISTRATOR'] },
        props: true,
      },
      {
        path: 'verification',
        name: 'VerificationQueue',
        component: () => import('../views/VerificationView.vue'),
        meta: {
          requiresAuth: true,
          roles: ['VERIFIER', 'CLINICAL_APPROVER', 'ADMINISTRATOR'],
        },
      },
      {
        path: 'verification/:batchId',
        name: 'VerificationBatch',
        component: () => import('../views/VerificationView.vue'),
        meta: {
          requiresAuth: true,
          roles: ['VERIFIER', 'CLINICAL_APPROVER', 'ADMINISTRATOR'],
        },
        props: true,
      },
      {
        path: 'approval',
        name: 'ApprovalQueue',
        component: () => import('../views/ApprovalView.vue'),
        meta: {
          requiresAuth: true,
          roles: ['CLINICAL_APPROVER', 'ADMINISTRATOR'],
        },
      },
      {
        path: 'approval/:batchId',
        name: 'ApprovalBatch',
        component: () => import('../views/ApprovalView.vue'),
        meta: {
          requiresAuth: true,
          roles: ['CLINICAL_APPROVER', 'ADMINISTRATOR'],
        },
        props: true,
      },
      {
        path: 'patients/:patientId/history',
        name: 'PatientHistory',
        component: () => import('../views/PatientHistoryView.vue'),
        meta: { requiresAuth: true },
        props: true,
      },
      {
        path: 'patients',
        name: 'PatientSearch',
        component: () => import('../views/PatientHistoryView.vue'),
        meta: { requiresAuth: true },
      },
      {
        path: 'live-capture',
        name: 'LiveCapture',
        component: () => import('../views/LiveCaptureView.vue'),
        meta: { requiresAuth: true, roles: ['CLINICIAN', 'ADMINISTRATOR'] },
      },
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('../views/QueueDashboardView.vue'),
        meta: { requiresAuth: true, roles: ['ADMINISTRATOR'] },
      },
      {
        path: 'fhir-explorer',
        name: 'FhirExplorer',
        component: () => import('../views/FhirExplorerView.vue'),
        meta: { requiresAuth: true, roles: ['ADMINISTRATOR'] },
      },
    ],
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/login',
  },
]

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

// Navigation guard: check auth and role
router.beforeEach((to, _from, next) => {
  const auth = useAuthStore()

  if (to.path === '/login' && auth.isAuthenticated) {
    return next(getDefaultRouteForRole(auth.userRole))
  }

  if (to.meta.requiresAuth && !auth.isAuthenticated) {
    return next('/login')
  }

  if (to.meta.roles && Array.isArray(to.meta.roles)) {
    const allowedRoles = to.meta.roles as string[]
    if (!allowedRoles.includes(auth.userRole)) {
      const fallback = getDefaultRouteForRole(auth.userRole)
      if (fallback !== '/login' && fallback !== to.path) {
        return next(fallback)
      }
      return next('/login')
    }
  }

  next()
})

export default router
