import { createRouter, createWebHistory } from 'vue-router';
import { sessionStore } from '@/stores/session';
import HomeView from '@/views/public/HomeView.vue';
import AnnouncementListView from '@/views/public/AnnouncementListView.vue';
import AnnouncementDetailView from '@/views/public/AnnouncementDetailView.vue';
import VerificationView from '@/views/public/VerificationView.vue';
import AuthView from '@/views/public/AuthView.vue';
import CandidatePage from '@/views/candidate/CandidatePage.vue';
import AdminPage from '@/views/admin/AdminPage.vue';
import AdmissionPage from '@/views/admission/AdmissionPage.vue';
import NotFoundView from '@/views/public/NotFoundView.vue';

const candidatePages = [
  ['onboarding', '首次登录'], ['dashboard', '总览'], ['profile', '个人资料'], ['exams', '考试报名'],
  ['registrations', '我的报名'], ['admit', '准考证'], ['results', '成绩查询'],
  ['admissions', '志愿与录取'], ['notices', '通知公告'], ['security', '账户安全']
];

const adminPages = [
  ['dashboard', '考务工作台'], ['schools', '学校管理'], ['organization', '本校组织'],
  ['admins', '管理员'], ['account-batches', '批量建号'], ['candidates', '考生信息'],
  ['indicator-qualifications', '指标资格确认'], ['registrations', '报名审核'], ['payments', '缴费名单'],
  ['admit', '准考证编排'], ['exams', '考试与科目'], ['results', '成绩管理'],
  ['admission-settings', '录取设置'], ['admission-accounts', '招生账户'],
  ['admission-plans', '招生计划'], ['admission-reporting', '报到与补录'],
  ['admission-supervision', '投档监督'], ['notices', '通知发布'], ['centers', '考场信息'],
  ['flows', '流程中心'], ['flow-design', '流程设计'], ['number-rules', '报名号规则'], ['security', '账户安全']
];

const admissionPages = [
  ['dashboard', '招生工作台'], ['plans', '招生计划'], ['placements', '投档审核'],
  ['reporting', '考生报到'], ['notice-template', '通知书模板']
];

const routes = [
  { path: '/', name: 'home', component: HomeView, meta: { public: true, title: '首页' } },
  { path: '/announcements', name: 'announcements', component: AnnouncementListView, meta: { public: true, title: '通知公告' } },
  { path: '/announcements/:id', name: 'announcement-detail', component: AnnouncementDetailView, meta: { public: true, title: '公告详情' } },
  { path: '/verify/:code?', name: 'verification', component: VerificationView, meta: { public: true, title: '文书防伪查询' } },
  { path: '/auth/login', name: 'login', component: AuthView, props: { mode: 'login' }, meta: { public: true, guest: true, title: '登录' } },
  { path: '/auth/register', name: 'register', component: AuthView, props: { mode: 'register' }, meta: { public: true, guest: true, title: '考生注册' } },
  { path: '/candidate', redirect: '/candidate/dashboard' },
  ...candidatePages.map(([page, title]) => ({
    path: `/candidate/${page}`,
    name: `candidate-${page}`,
    component: CandidatePage,
    props: { page },
    meta: { roles: ['candidate'], title }
  })),
  { path: '/admin', redirect: '/admin/dashboard' },
  ...adminPages.map(([page, title]) => ({
    path: `/admin/${page}`,
    name: `admin-${page}`,
    component: AdminPage,
    props: { page },
    meta: { roles: ['admin'], title }
  })),
  { path: '/admission', redirect: '/admission/dashboard' },
  ...admissionPages.map(([page, title]) => ({
    path: `/admission/${page}`,
    name: `admission-${page}`,
    component: AdmissionPage,
    props: { page },
    meta: { roles: ['admission_school'], title }
  })),
  { path: '/:pathMatch(.*)*', name: 'not-found', component: NotFoundView, meta: { public: true, title: '页面不存在' } }
];

export const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) return savedPosition;
    if (to.hash) return { el: to.hash, behavior: 'smooth' };
    return { top: 0 };
  }
});

router.beforeEach(async to => {
  try {
    await sessionStore.bootstrap();
  } catch {
    if (!to.meta.public) return { name: 'home' };
  }

  const user = sessionStore.state.user;
  if (to.meta.guest && user) return sessionStore.homeFor(user);
  if (to.meta.roles?.length) {
    if (!user) return { name: 'login', query: { redirect: to.fullPath } };
    if (!to.meta.roles.includes(user.role)) return sessionStore.homeFor(user);
    if (user.role === 'candidate' && to.path !== '/candidate/onboarding') {
      if (user.mustChangePassword || !sessionStore.state.profile?.profileCompleted) return '/candidate/onboarding';
    }
  }
  document.title = `${to.meta.title || '服务'} · 衡准考试信息管理系统`;
  return true;
});

export { candidatePages, adminPages, admissionPages };
