import { createRouter, createWebHistory } from 'vue-router';
import { useLayoutStore } from '@/store/layoutStore';
import authLayout from '@/layouts/auth-layout.vue';
import { usePermissions } from '@/composables/use-permissions';

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/index.vue'),
  },
  {
    path: '/auth/login',
    component: authLayout,
    children: [
      {
        path: '',
        name: 'login-route',
        component: () => import('@/views/auth/login.vue'),
        meta: { layout: 'auth' },
      },
      {
        path: '/auth/pass-recovery-boxed',
        name: 'pass-recovery-boxed',
        component: () => import('@/views/auth/pass_recovery_boxed.vue'),
        meta: { layout: 'auth' },
      },
      {
        path: '/auth/changepw/:uuid',
        name: 'router-changepw-externo',
        component: () => import('@/views/users/changepw.vue'),
        meta: { layout: 'auth' },
      },
    ],
  },
  {
    path: '/users/profile',
    name: 'users-profile-router',
    component: () => import('@/views/users/profile.vue'),
  },
  {
    path: '/users/lista',
    name: 'users-lista-router',
    component: () => import('@/views/users/index.vue'),
    meta: { permission: 'administracion.usuarios' },
  },
  {
    path: '/ganaderia/dashboard',
    name: 'ranch-dashboard',
    component: () => import('@/views/ranch/dashboard.vue'),
    meta: { permission: 'ranch.dashboard' },
  },
  {
    path: '/ganaderia/alertas',
    name: 'ranch-alert-center',
    component: () => import('@/views/ranch/alert-center.vue'),
    meta: { permission: ['ranch.dashboard', 'ranch.reports.view', 'ranch.cattle.view'] },
  },
  {
    path: '/ganaderia/animales',
    name: 'ranch-animals',
    component: () => import('@/views/ranch/animals.vue'),
    meta: { permission: ['ranch.cattle.view', 'ranch.cattle.manage'] },
  },
  {
    path: '/ganaderia/inventario-ubicacion',
    name: 'ranch-inventory-report',
    component: () => import('@/views/ranch/inventory-report.vue'),
    meta: { permission: 'ranch.cattle.view' },
  },
  {
    path: '/ganaderia/animales/:id',
    name: 'ranch-animal-detail',
    component: () => import('@/views/ranch/animal-detail.vue'),
    meta: { permission: ['ranch.cattle.view', 'ranch.cattle.manage'] },
  },
  {
    path: '/ganaderia/pesajes',
    name: 'ranch-weighings',
    component: () => import('@/views/ranch/weighings.vue'),
    meta: { permission: 'ranch.weight.record' },
  },
  {
    path: '/ganaderia/salud',
    name: 'ranch-health',
    component: () => import('@/views/ranch/health-events.vue'),
    meta: { permission: ['ranch.health.manage', 'ranch.health.view'] },
  },
  {
    path: '/ganaderia/bajas',
    name: 'ranch-deactivation',
    component: () => import('@/views/ranch/deactivation.vue'),
    meta: { permission: 'ranch.cattle.manage' },
  },
  {
    path: '/ganaderia/partos',
    name: 'ranch-calvings',
    component: () => import('@/views/ranch/calvings.vue'),
    meta: { permission: 'ranch.cattle.manage' },
  },
  {
    path: '/ganaderia/movimientos',
    name: 'ranch-location-movements',
    component: () => import('@/views/ranch/location-movements.vue'),
    meta: { permission: ['ranch.cattle.view', 'ranch.cattle.manage'] },
  },
  {
    path: '/ganaderia/potreros',
    name: 'ranch-pastures',
    component: () => import('@/views/ranch/pastures.vue'),
    meta: { permission: 'ranch.cattle.manage' },
  },
  {
    path: '/ganaderia/engorda',
    name: 'ranch-fattening',
    component: () => import('@/views/ranch/fattening-lots.vue'),
    meta: { permission: 'ranch.fattening.manage' },
  },
  {
    path: '/ganaderia/alimentos',
    name: 'ranch-feed-catalog',
    component: () => import('@/views/ranch/feed-catalog.vue'),
    meta: { permission: ['ranch.expenses.manage', 'ranch.fattening.manage'] },
  },
  {
    path: '/ganaderia/lotes-cerrados',
    name: 'ranch-closed-lots-ranking',
    component: () => import('@/views/ranch/closed-lots-ranking.vue'),
    meta: { permission: ['ranch.reports.view', 'ranch.fattening.manage'] },
  },
  {
    path: '/ganaderia/engorda-proyeccion',
    name: 'ranch-open-lots-projection',
    component: () => import('@/views/ranch/open-lots-projection.vue'),
    meta: { permission: ['ranch.reports.view', 'ranch.fattening.manage'] },
  },
  {
    path: '/ganaderia/engorda/:id',
    name: 'ranch-fattening-detail',
    component: () => import('@/views/ranch/fattening-lot-detail.vue'),
    meta: { permission: 'ranch.fattening.manage' },
  },
  {
    path: '/ganaderia/compras',
    name: 'ranch-purchases',
    component: () => import('@/views/ranch/expenses.vue'),
    meta: { permission: 'ranch.expenses.manage' },
  },
  {
    path: '/ganaderia/gastos',
    redirect: '/ganaderia/compras',
  },
  {
    path: '/ganaderia/reportes',
    name: 'ranch-reports',
    component: () => import('@/views/ranch/reports.vue'),
    meta: { permission: 'ranch.reports.view' },
  },
  {
    path: '/ganaderia/rentabilidad',
    name: 'ranch-animal-profitability',
    component: () => import('@/views/ranch/animal-profitability.vue'),
    meta: { permission: 'ranch.reports.view' },
  },
  {
    path: '/ganaderia/alertas-costo',
    name: 'ranch-cost-alerts',
    component: () => import('@/views/ranch/cost-alerts.vue'),
    meta: { permission: ['ranch.reports.view', 'ranch.cattle.view'] },
  },
  {
    path: '/ganaderia/rendimiento-peso',
    name: 'ranch-weight-performance',
    component: () => import('@/views/ranch/weight-performance.vue'),
    meta: { permission: ['ranch.reports.view', 'ranch.cattle.view'] },
  },
  {
    path: '/ganaderia/vacas-madre',
    name: 'ranch-mother-performance',
    component: () => import('@/views/ranch/mother-performance.vue'),
    meta: { permission: ['ranch.reports.view', 'ranch.cattle.view'] },
  },
  {
    path: '/ganaderia/respaldo-db',
    name: 'ranch-db-backup',
    component: () => import('@/views/ranch/database-backup.vue'),
    meta: { permission: 'administracion.usuarios' },
  },
  {
    path: '/admin/configuracion-empresa',
    name: 'admin-configuracion-empresa',
    component: () => import('@/views/admin/configuracion-empresa.vue'),
    meta: { permission: 'administracion.usuarios' },
  },
  {
    path: '/roles/lista',
    name: 'roles-lista-router',
    component: () => import('@/views/roles/index.vue'),
    meta: { permission: 'administracion.roles' },
  },
];

const router = createRouter({
  history: createWebHistory(),
  linkExactActiveClass: 'active',
  routes,
  scrollBehavior(to, from, savedPosition) {
    return savedPosition || { left: 0, top: 0 };
  },
});

router.beforeEach(async (to, from, next) => {
  const layoutStore = useLayoutStore();
  const token = window.localStorage.getItem('token');

  if (to.meta?.layout === 'auth') {
    layoutStore.setLayout('auth');
  } else {
    layoutStore.setLayout('app');
  }

  if (to.meta?.public) {
    next();
    return;
  }

  // Login / auth: si hay token inválido o sesión marcada, no entrar al panel.
  if (to.name === 'login-route') {
    if (to.query?.session) {
      window.localStorage.removeItem('token');
      next();
      return;
    }
    if (token) {
      try {
        const { loadPermissions, hasUsableAccess, resetPermissions } = usePermissions();
        resetPermissions();
        await loadPermissions({ force: true });
        if (hasUsableAccess()) {
          layoutStore.setLayout('app');
          next('/');
          return;
        }
        window.localStorage.removeItem('token');
        resetPermissions();
        next({ name: 'login-route', query: { session: 'noperms' }, replace: true });
        return;
      } catch {
        window.localStorage.removeItem('token');
        next();
        return;
      }
    }
    next();
    return;
  }

  // Otras pantallas de autenticación (recuperar / cambiar clave) sin token.
  if (to.meta?.layout === 'auth') {
    next();
    return;
  }

  if (!token) {
    next({ name: 'login-route', query: { session: 'auth' } });
    return;
  }

  // Rutas del panel: exigir sesión usable (token + permisos).
  try {
    const { loadPermissions, hasPermission, hasAnyPermission, hasUsableAccess } = usePermissions();
    await loadPermissions();

    if (!hasUsableAccess()) {
      window.localStorage.removeItem('token');
      usePermissions().resetPermissions();
      next({ name: 'login-route', query: { session: 'noperms' }, replace: true });
      return;
    }

    if (to.meta?.permission) {
      const required = to.meta.permission;
      const hasAccess = Array.isArray(required)
        ? hasAnyPermission(required)
        : hasPermission(required);
      if (!hasAccess) {
        next({ name: 'Home', replace: true });
        return;
      }
    }

    if (to.name === 'Home') {
      if (hasPermission('ranch.dashboard')) {
        next({ name: 'ranch-dashboard', replace: true });
        return;
      }
      if (hasPermission('ranch.cattle.view')) {
        next({ name: 'ranch-animals', replace: true });
        return;
      }
      if (hasPermission('administracion.usuarios')) {
        next({ path: '/admin/configuracion-empresa', replace: true });
        return;
      }
      // Sin módulos útiles: no mandar a perfil vacío
      window.localStorage.removeItem('token');
      usePermissions().resetPermissions();
      next({ name: 'login-route', query: { session: 'noperms' }, replace: true });
      return;
    }
  } catch (error) {
    if (import.meta.env.DEV) console.error(error);
    window.localStorage.removeItem('token');
    next({ name: 'login-route', query: { session: 'expired' }, replace: true });
    return;
  }

  next();
});

export default router;
