import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/LoginView.vue'),
    meta: { title: '登录', public: true },
  },
  {
    path: '/',
    component: () => import('@/layouts/DefaultLayout.vue'),
    redirect: '/goods',
    children: [
      {
        path: 'goods',
        name: 'Goods',
        component: () => import('@/views/product-management/ProductManagementView.vue'),
        meta: { title: '商品管理' },
      },
    ],
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/goods',
  },
]

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

router.beforeEach((to) => {
  const authStore = useAuthStore()
  const isPublic = to.meta?.public === true

  if (!authStore.isLoggedIn && !isPublic) {
    return { path: '/login', replace: true }
  }

  if (authStore.isLoggedIn && to.path === '/login') {
    return { path: '/', replace: true }
  }

  return true
})

router.afterEach((to) => {
  const title = (to.meta?.title as string) || 'Inkreach 官网后台'
  document.title = `${title} | Inkreach 官网后台`
})

export default router
