import { createRouter, createWebHistory } from 'vue-router';
import BoothLogin from '../views/BoothLogin.vue';
import VotingFlow from '../views/VotingFlow.vue';
import AdminDashboard from '../views/AdminDashboard.vue';
import Setup from '../views/Setup.vue';
import { authService } from '../services/api';

const routes = [
  {
    path: '/setup',
    name: 'Setup',
    component: Setup
  },
  {
    path: '/',
    name: 'Login',
    component: BoothLogin
  },
  {
    path: '/vote',
    name: 'Vote',
    component: VotingFlow,
    meta: { requiresAuth: true, role: 'booth' }
  },
  {
    path: '/admin',
    name: 'Admin',
    component: AdminDashboard,
    meta: { requiresAuth: true, role: 'admin' }
  }
];

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

let isConfigured = null;

router.beforeEach(async (to, from, next) => {
  // 1. Check if system is configured
  if (isConfigured === null) {
    try {
      const { data } = await authService.checkStatus();
      isConfigured = data.configured;
    } catch (err) {
      console.error('Failed to check configuration status:', err);
      // If we can't reach the server, don't redirect to setup. 
      // Instead, allow the navigation to proceed to the target page which will likely fail its own API calls,
      // providing a better error context than a forced setup screen.
      return next(); 
    }
  }

  if (isConfigured === false && to.name !== 'Setup') {
    return next('/setup');
  }

  if (isConfigured === true && to.name === 'Setup') {
    return next('/');
  }

  // 2. Auth checks
  const token = localStorage.getItem('token');
  const role = localStorage.getItem('role');

  if (to.meta.requiresAuth && !token) {
    next('/');
  } else if (to.meta.role && to.meta.role !== role) {
    next('/');
  } else {
    next();
  }
});

export default router;
