import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth'
import HomeView from '@/views/HomeView.vue'
import LoginView from '@/views/LoginView.vue'
import RegisterView from '@/views/RegisterView.vue'
import GenerateView from '@/views/GenerateView.vue'
import DiagramCenterView from '@/views/DiagramCenterView.vue'
import ModuleDiagramEditorView from '@/views/ModuleDiagramEditorView.vue'
import PageDesignerView from '@/views/PageDesignerView.vue'
import PaperDraftView from '@/views/PaperDraftView.vue'
import ProjectListView from '@/views/ProjectListView.vue'
import PreviewView from '@/views/PreviewView.vue'
import ProfileView from '@/views/ProfileView.vue'
import SourceDetailView from '@/views/SourceDetailView.vue'
import SourceStoreView from '@/views/SourceStoreView.vue'

const routes = [
  { path: '/', name: 'home', component: HomeView },
  { path: '/login', name: 'login', component: LoginView },
  { path: '/register', name: 'register', component: RegisterView },
  { path: '/source-store', name: 'source-store', component: SourceStoreView },
  { path: '/source-store/:sourceId', name: 'source-detail', component: SourceDetailView },
  { path: '/profile', name: 'profile', component: ProfileView, meta: { requiresAuth: true } },
  { path: '/projects', name: 'projects', component: ProjectListView, meta: { requiresAuth: true } },
  { path: '/generate', name: 'generate', component: GenerateView, meta: { requiresAuth: true } },
  {
    path: '/project/:projectId/page-designer',
    name: 'page-designer',
    component: PageDesignerView,
    meta: { requiresAuth: true }
  },
  {
    path: '/project/:projectId/diagrams',
    name: 'diagram-center',
    component: DiagramCenterView,
    meta: { requiresAuth: true }
  },
  {
    path: '/module-diagram',
    name: 'module-diagram-editor-local',
    component: ModuleDiagramEditorView
  },
  {
    path: '/project/:projectId/module-diagram',
    name: 'module-diagram-editor',
    component: ModuleDiagramEditorView,
    meta: { requiresAuth: true }
  },
  {
    path: '/project/:projectId/paper-draft',
    name: 'paper-draft',
    component: PaperDraftView,
    meta: { requiresAuth: true }
  },
  {
    path: '/project/:projectId/preview',
    name: 'preview',
    component: PreviewView,
    meta: { requiresAuth: true }
  }
]

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

router.beforeEach((to) => {
  if (to.meta.requiresAuth && !getToken()) {
    ElMessage.warning('请先登录后再使用生成工作台')
    return { path: '/login', query: { redirect: to.fullPath } }
  }

  return true
})

export default router
