// src/client/app/main.ts
// Vue application entry point

import './index.css';
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';
import { createRouter, createWebHistory } from 'vue-router';
import FloatingVue from 'floating-vue';
import 'floating-vue/dist/style.css';
import App from './App.vue';
import { useUserStore } from '../entities/user';
import { useAppConfigStore } from '../entities/appConfig';

// Import route configurations from modules
import { dashboardRoutes } from '../pages/dashboard.routes';
import { sharedRoutes } from '../shared/routes';

// Create router with aggregated routes from modules
export const router = createRouter({
  history: createWebHistory(),
  routes: [...sharedRoutes, ...dashboardRoutes],
});

// Navigation guard for protected routes
router.beforeEach(async (to, _from, next) => {
  const userStore = useUserStore();
  const appConfigStore = useAppConfigStore();
  
  // Check if route requires authentication
  if (to.meta.requiresAuth) {
    // Verify user is authenticated and has valid user data
    const isAuth = userStore.checkAuth();
    const hasUserData = userStore.user !== null;
    
    // If not authenticated or no user data, redirect to login
    if (!isAuth || !hasUserData) {
      // Clear any stale user data
      userStore.clearUser();
      
      // Redirect to login with reason
      const reason = hasUserData ? 'session_invalid' : 'session_expired';
      next(`/login?reason=${reason}`);
      return;
    }
  }
  
  // If user is authenticated and tries to access login page, redirect to dashboard
  if (to.path === '/login' && userStore.isAuthenticated && userStore.user !== null) {
    next('/dashboard/notes');
    return;
  }
  
  // Check if route has a module associated with it
  const routeModuleName = to.meta.moduleName as string | undefined;
  if (routeModuleName) {
    // Ensure app config is loaded
    if (!appConfigStore.isLoaded) {
      try {
        await appConfigStore.fetchConfig();
      } catch (error) {
        console.error('[Navigation Guard] Failed to fetch app config:', error);
        // Continue anyway, but log the error
      }
    }
    
    // Check if the module is enabled
    if (!appConfigStore.isModuleEnabled(routeModuleName)) {
      // Module is disabled, show notification and redirect to dashboard
      const moduleNames: Record<string, string> = {
        notes: 'Заметки',
        personnel: 'Сотрудники',
        schedule: 'График смен',
        blacklist: 'Черный список',
        reference_books: 'Справочники',
        rooms: 'База номеров',
        operations: 'Текущие операции',
        tasks: 'Задачи',
      };
      const moduleDisplayName = moduleNames[routeModuleName] || routeModuleName;
      alert(`Модуль "${moduleDisplayName}" отключен администратором`);
      console.warn(`[Navigation Guard] Module "${routeModuleName}" is disabled, redirecting to dashboard`);
      next('/dashboard/notes');
      return;
    }
  }
  
  next();
});

const app = createApp(App);
const pinia = createPinia();

pinia.use(piniaPluginPersistedstate);

app.use(pinia);

// Инициализируем глобальный обработчик для очистки пользователя (используется в api.client.ts)
const userStore = useUserStore();
window.clearUser = () => userStore.clearUser();
app.use(router);
app.use(FloatingVue);
app.mount('#app');
