import { createRouter, createWebHistory } from "vue-router";

// Import your route modules
import authRoutes from '../pages/auth/routes.ts';
import oilRoutes from '../pages/delivery/routes.ts';
import employeeRoutes from '../pages/employee/routes.ts';
import payRoutes from '../pages/pay/routes.ts';
import customerRoutes from '../pages/customer/routes.ts';
import cardRoutes from '../pages/card/routes.ts';
import autoRoutes from '../pages/automatic/routes.ts';
import adminRoutes from "../pages/admin/routes.ts";
import tickerRoutes from "../pages/ticket/routes.ts";
import serviceRoutes from "../pages/service/routes.ts";
import transactionsRoutes from '../pages/transactions/routes.ts';
import statsRoutes from '../pages/stats/routes.ts';

// Import your page components
import Home from '../pages/Index.vue';
import Error404 from '../pages/error/Error404.vue';
import PricingHistory from '../pages/info/PricingHistory.vue';

// Import layouts
import DefaultLayout from '../layouts/DefaultLayout.vue';
import BlankLayout from '../layouts/BlankLayout.vue';

// Import the Pinia Stores
import { useAuthStore } from '../stores/auth.ts';
import { useCountsStore } from '../stores/counts.ts';

// Your protectRoutes function and routes array remain the same...
const protectRoutes = (routes: any[]) => {
  return routes.map(route => {
    route.meta = { ...route.meta, requiresAuth: true };
    if (route.children) {
      route.children = protectRoutes(route.children);
    }
    return route;
  });
};

const routes = [
  // Auth routes (no layout needed, they handle their own)
  ...authRoutes,

  // Default layout routes
  {
    path: '/',
    component: DefaultLayout,
    children: [
      ...protectRoutes(cardRoutes),
      ...protectRoutes(payRoutes),
      ...protectRoutes(employeeRoutes),
      ...protectRoutes(customerRoutes),
      ...protectRoutes(oilRoutes),
      ...protectRoutes(autoRoutes),
      ...protectRoutes(adminRoutes),
      ...protectRoutes(serviceRoutes),
      ...protectRoutes(transactionsRoutes),
      ...protectRoutes(statsRoutes),

      {
        path: '',
        name: 'home',
        component: Home,
        meta: { requiresAuth: true }
      },
      {
        path: '/info/pricing-history',
        name: 'PricingHistory',
        component: PricingHistory,
        meta: { requiresAuth: true }
      },
      {
        path: '/error404',
        name: 'Error404',
        component: Error404,
        meta: { requiresAuth: false }
      },
    ]
  },

  // Blank layout for ticket pages
  {
    path: '/ticket',
    component: BlankLayout,
    children: protectRoutes(tickerRoutes)
  },
];

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

// Your beforeEach guard remains the same...
// @ts-ignore
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore();
  const isAuthenticated = await authStore.checkAuthStatus();
  const requiresAuth = to.meta.requiresAuth;

  if (requiresAuth && !isAuthenticated) {
    next({ name: 'login' });
  } else if (to.name === 'login' && isAuthenticated) {
    next({ name: 'home' });
  } else {
    next();
  }
});

// --- DATA FETCHING GUARD (runs AFTER navigation is confirmed) ---
// THIS IS THE CORRECTED BLOCK
router.afterEach((_to: any, _from: any) => {
  // We add types and prefix with `_` to signal they are unused.
  const countsStore = useCountsStore();
  const authStore = useAuthStore();

  if (authStore.isAuthenticated) {
    console.log('Navigation complete, fetching sidebar counts...');
    countsStore.fetchSidebarCounts();
  }
});

export default router;
