import {
  createRouter,
  createWebHistory,
  RouteRecordRaw,
} from 'vue-router';
import RegisterView from '@/views/RegisterView.vue';
import LoginView from '@/views/LoginView.vue';
import {
  Privileges,
  SuccessResponse,
} from '@/api/types';
import HomeView from '@/views/HomeView.vue';
import FundView from '@/views/FundView.vue';
import AddFundView from '@/views/AddFundView.vue';
import hasPermission from '@/lib/auth';
import SignetRequestController from '@/api/requests';

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { title: 'Home' },
  },
  {
    path: '/fund/:id',
    name: 'fund',
    component: FundView,
    meta: { title: undefined },
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView,
    meta: { title: 'Login' },
  },
  {
    path: '/register',
    name: 'register',
    component: RegisterView,
    meta: {
      requiredRights: Privileges.AdminPlus,
      accessible: async () => {
        const controller = new SignetRequestController();
        const canProceed = await controller.post<SuccessResponse, null>('/UsersExist', null);
        return canProceed?.success;
      },
      title: 'Register',
    },
  },
  {
    path: '/addfund',
    name: 'addfund',
    component: AddFundView,
    meta: {
      requiredRights: Privileges.Admin,
      title: 'Add Group Fund',
    },
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

router.beforeEach(async (to, from, next) => {
  document.title = `Beignet - ${to.meta.title}`;

  const requiredRights = to.meta.requiredRights as number | undefined;
  const accessible = to.meta.accessible as (() => SuccessResponse) | undefined;
  const allowed = requiredRights ? hasPermission(requiredRights)
    || (accessible && !accessible().success) : true;

  if (allowed) {
    next();
  } else {
    next('/');
  }
});

export default router;
