import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import axios from 'axios'

// Configure axios
window.axios = axios
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'

// Get CSRF token
const token = document.head.querySelector('meta[name="csrf-token"]')
if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content
} else {
    console.error('CSRF token not found')
}

// Import dashboard components
import DashboardLayout from './components/dashboard/DashboardLayout.vue'
import DoctorDashboard from './components/dashboard/DoctorDashboard.vue'
import PatientDashboard from './components/dashboard/PatientDashboard.vue'
import AdminDashboard from './components/dashboard/AdminDashboard.vue'
import NurseDashboard from './components/dashboard/NurseDashboard.vue'

// Dashboard router configuration
const routes = [
    {
        path: '/doctor-dashboard',
        name: 'DoctorDashboard',
        component: DoctorDashboard,
        meta: { role: 'doctor' }
    },
    {
        path: '/patient-dashboard',
        name: 'PatientDashboard',
        component: PatientDashboard,
        meta: { role: 'patient' }
    },
    {
        path: '/admin-dashboard',
        name: 'AdminDashboard',
        component: AdminDashboard,
        meta: { role: 'hospital_admin' }
    },
    {
        path: '/nurse-dashboard',
        name: 'NurseDashboard',
        component: NurseDashboard,
        meta: { role: 'nurse' }
    },
    // Default redirect based on role
    {
        path: '/',
        redirect: () => {
            const userRole = window.userRole || 'patient'
            return `/${userRole}-dashboard`
        }
    },
    // 404 redirect
    {
        path: '/:pathMatch(.*)*',
        redirect: () => {
            const userRole = window.userRole || 'patient'
            return `/${userRole}-dashboard`
        }
    }
]

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

// Route guard to check user role
router.beforeEach((to, from, next) => {
    const userRole = window.userRole
    const requiredRole = to.meta.role
    
    if (requiredRole && userRole !== requiredRole) {
        // Redirect to correct dashboard based on user role
        next(`/${userRole}-dashboard`)
    } else {
        next()
    }
})

// Create Vue app
const app = createApp(DashboardLayout)
app.use(router)
app.mount('#dashboard-app')