import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Carrier from '../views/Carrier.vue'
import CreateLane from '../views/CreateLane.vue'

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  { path: '/broker', component: CreateLane, meta: { requiresAuth: true, role: 'broker' } },
  { path: '/carrier', component: Carrier,   meta: { requiresAuth: true, role: 'carrier' } },
]

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

// Fetch the current session once per navigation.
async function getSession() {
  const res = await fetch('/me')
  if (!res.ok) return null
  const { data } = await res.json()
  return data
}

function homeForRole(role) {
  return role === 'broker' ? '/broker' : '/carrier'
}

router.beforeEach(async (to) => {
  const session = await getSession()

  if (to.path === '/login') {
    // Already logged in — send to the right home page.
    if (session) return homeForRole(session.role)
    return true
  }

  if (!session) return '/login'

  // Logged in but landed on the wrong role's page.
  if (to.meta.role && session.role !== to.meta.role) {
    return homeForRole(session.role)
  }

  return true
})

export default router
