import { createRouter, createWebHistory } from "vue-router";
import Dashboard from "./views/Dashboard.vue";
import CarDetail from "./views/CarDetail.vue";
import Charging from "./views/Charging.vue";
import Login from "./views/Login.vue";
import Settings from "./views/Settings.vue";
import { isAuthenticated } from "./auth";

const routes = [
  { path: "/login", name: "login", component: Login, meta: { public: true } },
  { path: "/", name: "dashboard", component: Dashboard },
  { path: "/charging", name: "charging", component: Charging },
  { path: "/cars/:id", name: "car", component: CarDetail, props: true },
  { path: "/settings", name: "settings", component: Settings },
  // User management moved into Settings; keep old links working.
  { path: "/admin", redirect: { name: "settings", query: { tab: "users" } } },
];

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

// Guard: protected routes require a token; visiting /login while authed bounces home.
router.beforeEach((to) => {
  if (!to.meta.public && !isAuthenticated.value) {
    return { name: "login", query: { redirect: to.fullPath } };
  }
  if (to.name === "login" && isAuthenticated.value) {
    return { name: "dashboard" };
  }
});

export default router;
