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

// Nézetek importálása
import Dashboard from '../views/Dashboard.vue';
import Expenses from '../views/Expenses.vue';
import AddExpense from '../views/AddExpense.vue';
import Login from '../views/Login.vue';
import Register from '../views/Register.vue';
import ForgotPassword from '../views/ForgotPassword.vue';
import ResetPassword from '../views/ResetPassword.vue';
import AddVehicle from '../views/AddVehicle.vue';
import AdminStats from '../views/admin/AdminStats.vue';

const routes = [
  // Védett útvonalak
  { path: '/', name: 'Dashboard', component: Dashboard, meta: { requiresAuth: true } },
  { path: '/expenses', name: 'Expenses', component: Expenses, meta: { requiresAuth: true } },
  { path: '/expenses/add', name: 'AddExpense', component: AddExpense, meta: { requiresAuth: true } },
  { path: '/vehicles/add', name: 'AddVehicle', component: AddVehicle, meta: { requiresAuth: true } },
  
  // ADMIN útvonal
  { 
    path: '/admin', 
    name: 'Admin', 
    component: AdminStats, 
    meta: { requiresAuth: true, requiresAdmin: true } 
  },

  // Nyilvános útvonalak
  { path: '/login', name: 'Login', component: Login },
  { path: '/register', name: 'Register', component: Register },
  { path: '/forgot-password', name: 'ForgotPassword', component: ForgotPassword },
  { path: '/reset-password', name: 'ResetPassword', component: ResetPassword },
];

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

// A "SOROMPÓ" (Auth Guard) LOGIKA
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  // Egyszerűsített admin check (később a JWT-ből decodoljuk)
  const isAdmin = localStorage.getItem('is_admin') === 'true';

  if (to.meta.requiresAuth && !token) {
    next('/login');
  } else if (to.meta.requiresAdmin && !isAdmin) {
    // Ha admin oldalra menne, de nem admin, dobja a főoldalra
    next('/');
  } else {
    next();
  }
});

export default router;