import { tempErrorRouteName, usePageStore } from '@/stores/page';
import { useUserStore } from '@/stores/user';
import { PageErrorType, type PageErrorReason } from '@/views/ErrorPage.vue';
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router';
import { RoutePermissionId } from './permissions';

declare module 'vue-router' {
  interface RouteMeta {
    permissionId?: RoutePermissionId;
    shouldLogin?: boolean;
    routeId?: number;
  }
}
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: () => import('@/views/MainPage.vue'),
  },
  {
    path: '/user/:id',
    component: () => import('@/views/UserPage.vue'),
  },
  {
    path: '/club',
    component: () => import('@/views/ClubPage.vue'),
    meta: {
      permissionId: RoutePermissionId.CLUB_PAGE,
    },
  },
  {
    path: '/2048',
    component: () => import('@/views/Game2048Page.vue'),
  },
  {
    path: '/gobang',
    name: 'GobangList',
    component: () => import('@/views/GobangListPage.vue'),
    meta: {
      shouldLogin: true,
    },
  },
  {
    path: '/gobang/single',
    name: 'GobangPlaySingle',
    component: () => import('@/views/GobangPlayPage.vue'),
    meta: {
      shouldLogin: true,
    },
  },
  {
    path: '/gobang/:id',
    name: 'GobangPlayMulti',
    component: () => import('@/views/GobangPlayPage.vue'),
    meta: {
      shouldLogin: true,
    },
  },
  {
    path: '/:path(.*)*',
    name: 'notFound',
    component: () => import('@/views/ErrorPage.vue'),
    props: {
      type: PageErrorType.NOT_FOUND,
    } satisfies PageErrorReason,
  },
];
const router = createRouter({
  history: createWebHistory(),
  routes: routes,
});

router.beforeEach(async (to) => {
  const userStore = useUserStore();
  const pageStore = usePageStore();
  const { permissionId } = to.meta;
  pageStore.setNewRouteId(to);
  if (!userStore.userInfo) {
    const succeed = await userStore.updateSelfUserInfo(true);
    if (!succeed) {
      if (permissionId === undefined) {
        return true;
      }
      return pageStore.createTempErrorRoute(
        {
          type: PageErrorType.NETWORK_ERROR,
        },
        to,
      );
    }
  }
  if (to.meta.shouldLogin && !userStore.logined) {
    return pageStore.createTempErrorRoute({ type: PageErrorType.NOT_LOGIN }, to);
  }
  if (permissionId) {
    if (userStore.hasPermission(permissionId)) {
      return true;
    } else {
      return pageStore.createTempErrorRoute({ type: PageErrorType.NO_PERMISSION }, to);
    }
  }
  return true;
});
router.afterEach((to) => {
  const pageStore = usePageStore();
  pageStore.removeRouteId(to);
  if (router.hasRoute(tempErrorRouteName)) {
    router.removeRoute(tempErrorRouteName);
  }
});
export default router;
