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

import HomeView from "../views/HomeView.vue"
import MarketplaceView from "../views/MarketplaceView.vue"
import ProductDetailView from "../views/ProductDetailView.vue"
import SellProductView from "../views/SellProductView.vue"
import DashboardView from "../views/DashboardView.vue"
import SavedView from "../views/SavedView.vue"
import LoginView from "../views/LoginView.vue"
import RegisterView from "../views/RegisterView.vue"
import AdminProductsView from "../views/AdminProductsView.vue"
import EditProductView from "../views/EditProductView.vue"
import { getCurrentUser, getToken } from "../utils"

const routes = [
  { path: "/", name: "home", component: HomeView },
  { path: "/marketplace", name: "marketplace", component: MarketplaceView },
  { path: "/produk/:id", name: "product-detail", component: ProductDetailView },
  { path: "/jual", name: "sell-product", component: SellProductView, meta: { requiresAuth: true } },
  { path: "/dashboard", name: "dashboard", component: DashboardView, meta: { requiresAuth: true } },
  { path: "/edit/:id", name: "edit-product", component: EditProductView, meta: { requiresAuth: true } },
  { path: "/tersimpan", name: "saved", component: SavedView, meta: { requiresAuth: true } },
  {
    path: "/admin/products",
    name: "admin-products",
    component: AdminProductsView,
    meta: { requiresAuth: true, requiresSuperadmin: true }
  },
  { path: "/login", name: "login", component: LoginView },
  { path: "/register", name: "register", component: RegisterView }
]

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

router.beforeEach((to) => {
  if (to.meta.requiresAuth && !getToken()) {
    return "/login"
  }

  const user = getCurrentUser()

  if (to.meta.requiresSuperadmin && user?.role !== "superadmin") {
    return "/dashboard"
  }
})

export default router
