// Composables
import { createRouter, createWebHistory } from "vue-router";
import { useStateStore } from '../store/StateStore';
import * as UserRepository from "@/repositories/UserRepository";

const routes = [
  {
    path: "/",
    component: () => import("@/layouts/app-layout.vue"),
    children: [
      {
        path: "",
        name: "home-route-principal",
        component: () => import("@/views/index.vue"),
        meta: { layout: 'app' },
      },
    ],
  },
  {
    path: "/auth/login",
    component: () => import("@/layouts/auth-layout.vue"),
    children: [
      {
        path: "",
        name: "login-route",
        component: () => import("@/views/auth/login_boxed.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/register',
        name: 'router-register-externo',
        component: () => import('@/views/users/registro.vue'),
        meta: { layout: 'auth' },
      },
      {
        path: '/auth/changepw/:uuid',
        name: 'router-changepw-externo',
        component: () => import('@/views/users/changepw.vue'),
        meta: { layout: 'auth' },
      },
    ],
  },
  {
    path: "/tienda",
    component: () => import("@/layouts/auth-layout.vue"),
    children: [
      {
        path: '',
        name: 'temp-router-tienda',
        component: () => import('@/views/productos/presentacion.vue'),
      },
    ],
  },
  {
    path: "",
    name: "home-route",
    component: () => import("@/views/index.vue"),
    meta: { layout: 'app' },
  },
  // Usuarios
  {
    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'),
  },
  //revision de usuario
  {
    path: '/users/revision',
    name: 'users-revision-router',
    component: () => import('@/views/users/revision.vue'),
  },
  //clientes
  {
    path: '/clientes/lista',
    name: 'clientes-lista-router',
    component: () => import('@/views/clientes/index.vue'),
  },
  //expedientes
  {
    path: '/expedientes/:clienteId',
    name: 'expedientes-clienteid-router',
    component: () => import('@/views/expedientes/index.vue'),
  },
  //tratamientos
  {
    path: '/tratamientos/lista',
    name: 'tratamientos-liste-router',
    component: () => import('@/views/tratamientos/index.vue'),
  },
  //sucursales
  {
    path: '/sucursales/lista',
    name: 'sucursales-liste-router',
    component: () => import('@/views/sucursales/index.vue'),
  },
   //horarios
   {
    path: '/horarios/lista',
    name: 'horarios-liste-router',
    component: () => import('@/views/horarios/index.vue'),
  },
  //monitor
  {
    path: '/monitor/:sucursalId?',
    name: 'citas-monitor-router',
    component: () => import('@/views/citas/monitor.vue'),
  },
  //otros
  {
    path: '/temp',
    name: 'temp-router',
    component: () => import(/* webpackChunkName: "components-modals" */ '../views/noterminado.vue'),
  },
  //citas
  {
    path: '/citas/reservar',
    name: 'calendar',
    component: () => import('@/views/citas/reservar.vue'),
  },
  //revision de citas
  {
    path: '/citas/confirmar',
    name: 'citas-confirmar-router',
    component: () => import('@/views/citas/revision.vue'),
  },
   //productos
  {
    path: '/productos/lista',
    name: 'productos-lista',
    component: () => import('@/views/productos/index.vue'),
  },
  //marcas
  {
    path: '/marcas/lista',
    name: 'marcas-lista',
    component: () => import('@/views/marcas/index.vue'),
  },
  //tipos servicios
  {
    path: '/productos/tipo-tratamiento',
    name: 'productos-tipo-tratamiento-lista',
    component: () => import('@/views/tiposServicios/index.vue'),
  },
  {
    path: '/productos/tipo',
    name: 'productos-tipo-lista',
    component: () => import('@/views/tiposProductos/index.vue'),
  },
   //ventas
  {
    path: '/ventas/vender',
    name: 'ventas-vender',
    component: () => import('@/views/ventas/vender.vue'),
  },
  {
    path: '/ventas/lista',
    name: 'ventas-lista',
    component: () => import('@/views/ventas/index.vue'),
  },
  {
    path: '/productos/presentacion',
    name: 'productos-presentacion',
    component: () => import('@/views/productos/presentacion.vue'),
  },
  {
    path: '/ventas/mis-compras',
    name: 'ventas-mis-ventas',
    component: () => import('@/views/ventas/mis_ventas.vue'),
  },
  {
    path: '/carrito/list',
    name: 'carrito-list',
    component: () => import('@/views/carrito/index.vue'),
  },
  {
    path: '/cortes-cajas/lista',
    name: 'cortes-cajas-lista',
    component: () => import('@/views/cortes/index.vue'),
  },
  //almacen
  {
    path: '/inventarios/lista',
    name: 'inventarios-lista',
    component: () => import('@/views/inventarios/index.vue'),
  },
  //entrada
  {
    path: '/entradas/lista',
    name: 'entradas-lista',
    component: () => import('@/views/entradas/index.vue'),
  },
  //salida
  {
    path: '/salidas/lista',
    name: 'salidas-lista',
    component: () => import('@/views/salidas/index.vue'),
  },
  //vales
  {
    path: '/vales/lista',
    name: 'vales-lista',
    component: () => import('@/views/vales/index.vue'),
  },
  //bancos
  {
    path: '/bancos/lista',
    name: 'bancos-lista',
    component: () => import('@/views/bancos/index.vue'),
  },
  //direcion entrega
  {
    path: '/direcciones/entrega/:clienteId',
    name: 'direcciones-entrega',
    component: () => import('@/views/direcciones/index.vue'),
  },
  //datos fiscales
  {
    path: '/datos-fiscales/lista/:clienteId',
    name: 'datos-fiscales-lista',
    component: () => import('@/views/datosFiscales/index.vue'),
  },
  //opciones de pago
  {
    path: '/opciones-pago-transferencia/lista',
    name: 'opciones-pago-transferencia-lista',
    component: () => import('@/views/opcionesPagos/index.vue'),
  },
  //configuración de impresiones
  {
    path: '/configuracion/impresoras',
    name: 'configuracion-impresoras',
    component: () => import('@/views/configuracion/ConfigImpresiones.vue'),
  },
  //configuración de correos
  {
    path: '/configuracion/correos',
    name: 'configuracion-correos',
    component: () => import('@/views/configuracion/ConfigCorreos.vue'),
  },
  //verificar
  {
    path: '/ventas/confirmar',
    name: 'ventas-confirmar',
    component: () => import('@/views/ventas/verificar.vue'),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

const obtener_user = async () => {
    try {
        const response = await UserRepository.getuser();
        return response;
    } catch (error) {
        console.log(error);
    }
};

router.beforeEach(async (to, from, next) => {
  const token = window.localStorage.getItem("token");
  if (to.meta && to.meta.layout && to.meta.layout == 'auth' || to.path == '/tienda' || to.path == '/auth/register' || (to.name == 'citas-monitor-router' && !token)) {
    useStateStore().current_state.layout='auth';
  } else {
    useStateStore().current_state.layout='app';
  }
  if (to.name !== 'login-route' && to.name !== 'registro-route' && !token && to.path !== '/tienda' && to.path !== '/auth/register' && to.name !== 'citas-monitor-router' && to.name !== 'router-changepw-externo') {
    // return { name: 'login-route' };
    next('/auth/login')
  } else if(token && to.name == 'login-route'){
    useStateStore().current_state.layout='app';
    // return { name: 'home-route' };
    next("/");
  }
  if (token && (to.name == 'home-route-principal' || to.name == 'home-route')) {
    const user = await obtener_user();
    if (user.roles['0'].name === 'Cliente') {
        if (user.tipo_cliente === "cliente_linea") {
            return next('/productos/presentacion');
        }
    }
  }
  next();
})

export default router;
