import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../components/Layout.vue'
import Dashboard from '../views/Dashboard.vue'
import ChannelSubject from '../views/ChannelSubject.vue'
import ChannelApp from '../views/ChannelApp.vue'
import ChannelAccount from '../views/ChannelAccount.vue'
import ChannelIdentity from '../views/ChannelIdentity.vue'
import Person from '../views/Person.vue'
import Conversation from '../views/Conversation.vue'
import Tag from '../views/Tag.vue'
import SendRecord from '../views/SendRecord.vue'
import Messages from '../views/Messages.vue'
import InboundFlow from '../views/InboundFlow.vue'
import TenantManagement from '../views/TenantManagement.vue'
import UserManagement from '../views/UserManagement.vue'
import Login from '../views/Login.vue'
import { useAuthStore } from '../stores/auth'

const routes = [
  {
    path: '/login',
    component: Login,
    meta: { public: true },
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      { path: 'dashboard', component: Dashboard, meta: { title: '概览' } },
      { path: 'channel/subject', component: ChannelSubject, meta: { title: '渠道主体' } },
      { path: 'channel/app', component: ChannelApp, meta: { title: '渠道应用' } },
      { path: 'channel/account', component: ChannelAccount, meta: { title: '渠道账号' } },
      { path: 'channel/identity', component: ChannelIdentity, meta: { title: '渠道身份' } },
      { path: 'customer/person', component: Person, meta: { title: '联系人' } },
      { path: 'customer/group', component: Conversation, meta: { title: '群聊' } },
      { path: 'customer/tag', component: Tag, meta: { title: '标签体系' } },
      { path: 'message/send-record', component: SendRecord, meta: { title: '发送记录' } },
      { path: 'message/query', component: Messages, meta: { title: '消息查询' } },
      { path: 'flow/inbound', component: InboundFlow, meta: { title: '入站流程' } },
      { path: 'system/tenant', component: TenantManagement, meta: { title: '租户管理' } },
      { path: 'system/user', component: UserManagement, meta: { title: '用户管理' } },
    ],
  },
]

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

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

  if (!isPublic && !authStore.isLoggedIn) {
    next('/login')
  } else if (to.path === '/login' && authStore.isLoggedIn) {
    next('/dashboard')
  } else {
    next()
  }
})

export default router
