import { createRouter, createWebHistory } from 'vue-router'
import { systemApi } from '../api'

const routes = [
  {
    path: '/install',
    name: 'Install',
    component: () => import('../views/Install.vue'),
    meta: { install: true },
  },
  {
    path: '/',
    component: () => import('../layouts/UserLayout.vue'),
    children: [
      { path: '', name: 'Home', component: () => import('../views/user/Home.vue') },
      { path: 'products', name: 'Products', component: () => import('../views/user/Products.vue') },
      { path: 'products/:id', name: 'ProductDetail', component: () => import('../views/user/ProductDetail.vue') },
      { path: 'cart', name: 'Cart', component: () => import('../views/user/Cart.vue') },
      { path: 'orders', name: 'Orders', component: () => import('../views/user/Orders.vue') },
      { path: 'orders/:id', name: 'OrderDetail', component: () => import('../views/user/OrderDetail.vue') },
      { path: 'checkout/:id', name: 'Checkout', component: () => import('../views/user/Checkout.vue') },
      { path: 'profile', name: 'Profile', component: () => import('../views/user/Profile.vue') },
      { path: 'addresses', name: 'Addresses', component: () => import('../views/user/Addresses.vue') },
      { path: 'lotteries', name: 'Lotteries', component: () => import('../views/user/Lotteries.vue') },
      { path: 'lotteries/:id', name: 'LotteryDetail', component: () => import('../views/user/LotteryDetail.vue') },
      { path: 'tickets', name: 'Tickets', component: () => import('../views/user/Tickets.vue') },
      { path: 'tickets/create', name: 'CreateTicket', component: () => import('../views/user/CreateTicket.vue') },
      { path: 'tickets/:id', name: 'TicketDetail', component: () => import('../views/user/TicketDetail.vue') },
      { path: 'articles', name: 'Articles', component: () => import('../views/user/Articles.vue') },
      { path: 'articles/:id', name: 'ArticleDetail', component: () => import('../views/user/ArticleDetail.vue') },
      { path: 'login', name: 'Login', component: () => import('../views/auth/Login.vue'), meta: { guest: true, hideSidebar: true } },
      { path: 'register', name: 'Register', component: () => import('../views/auth/Register.vue'), meta: { guest: true, hideSidebar: true } },
      { path: 'forgot-password', name: 'ForgotPassword', component: () => import('../views/auth/ForgotPassword.vue'), meta: { guest: true, hideSidebar: true } },
    ],
  },
  {
    path: '/admin',
    component: () => import('../layouts/AdminLayout.vue'),
    meta: { requiresAuth: true, role: 'admin' },
    children: [
      { path: '', name: 'AdminDashboard', component: () => import('../views/admin/Dashboard.vue') },
      { path: 'users', name: 'AdminUsers', component: () => import('../views/admin/Users.vue') },
      { path: 'categories', name: 'AdminCategories', component: () => import('../views/admin/Categories.vue') },
      { path: 'brands', name: 'AdminBrands', component: () => import('../views/admin/Brands.vue') },
      { path: 'products', name: 'AdminProducts', component: () => import('../views/admin/Products.vue') },
      { path: 'orders', name: 'AdminOrders', component: () => import('../views/admin/Orders.vue') },
      { path: 'suppliers', name: 'AdminSuppliers', component: () => import('../views/admin/Suppliers.vue') },
      { path: 'lotteries', name: 'AdminLotteries', component: () => import('../views/admin/Lotteries.vue') },
      { path: 'tickets', name: 'AdminTickets', component: () => import('../views/admin/Tickets.vue') },
      { path: 'settings', name: 'AdminSettings', component: () => import('../views/admin/Settings.vue') },
      { path: 'articles', name: 'AdminArticles', component: () => import('../views/admin/Articles.vue') },
      { path: 'banners', name: 'AdminBanners', component: () => import('../views/admin/Banners.vue') },
      { path: 'payment', name: 'AdminPayment', component: () => import('../views/admin/PaymentChannels.vue') },
      { path: 'logs', name: 'AdminLogs', component: () => import('../views/admin/Logs.vue') },
    ],
  },
  {
    path: '/supplier',
    component: () => import('../layouts/SupplierLayout.vue'),
    meta: { requiresAuth: true, role: 'supplier' },
    children: [
      { path: '', name: 'SupplierDashboard', component: () => import('../views/supplier/Dashboard.vue') },
      { path: 'orders', name: 'SupplierOrders', component: () => import('../views/supplier/Orders.vue') },
      { path: 'inventory', name: 'SupplierInventory', component: () => import('../views/supplier/Inventory.vue') },
    ],
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue'),
  },
]

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

let isInstalled = false

async function checkInstalled() {
  try {
    const res: any = await systemApi.checkInstalled()
    isInstalled = res.installed
    return isInstalled
  } catch {
    return true
  }
}

router.beforeEach(async (to, _from, next) => {
  const installed = await checkInstalled()

  if (!installed && to.path !== '/install') {
    next('/install')
    return
  }

  if (installed && to.path === '/install') {
    next('/')
    return
  }

  const token = localStorage.getItem('token')
  const userStr = localStorage.getItem('user')
  const user = userStr && userStr !== 'undefined' ? JSON.parse(userStr) : null

  if (to.meta.requiresAuth && !token) {
    next('/login')
  } else if (to.meta.role && user?.role !== to.meta.role && user?.role !== 'admin') {
    next('/')
  } else if (to.meta.guest && token) {
    next('/')
  } else {
    next()
  }
})

export default router
