import { createRouter, createWebHashHistory } from 'vue-router';
import { authState, checkAuth } from './store/auth.js';

const routes = [
  { path: '/login', name: 'login', component: () => import('./views/Login.vue'), meta: { public: true } },
  { path: '/', name: 'dashboard', component: () => import('./views/Dashboard.vue') },
  { path: '/product-groups', name: 'product-groups', component: () => import('./views/ProductGroups.vue') },
  { path: '/pricing', name: 'pricing', component: () => import('./views/Pricing.vue') },
  { path: '/imports', name: 'imports', component: () => import('./views/Imports.vue') },
  { path: '/imports/:id', name: 'import-onboarding', component: () => import('./views/ImportOnboarding.vue'), props: true },
  { path: '/stock', name: 'stock', component: () => import('./views/Stock.vue') },
];

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

router.beforeEach(async (to) => {
  if (!authState.checked) {
    await checkAuth();
  }
  if (!to.meta.public && !authState.authenticated) {
    return { name: 'login', query: { redirect: to.fullPath } };
  }
  if (to.name === 'login' && authState.authenticated) {
    return { name: 'dashboard' };
  }
  return true;
});

export default router;
