import { router } from '@/router.js';

function middlewarePipeline(context, middleware, index) {
  const nextMiddleware = middleware[index];

  if (!nextMiddleware) {
    return context.next;
  }

  return () => {
    const nextPipeline = middlewarePipeline(context, middleware, index + 1);
    nextMiddleware({ ...context, next: nextPipeline });
  };
}

export default function applyMiddleware(router) {
  router.beforeEach((to, from, next) => {
    if (!to.meta.middleware) {
      return next();
    }

    const middleware = Array.isArray(to.meta.middleware) ? to.meta.middleware : [to.meta.middleware];

    const context = {
      from,
      next,
      router,
      to,
    };

    const nextMiddleware = middlewarePipeline(context, middleware, 1);

    return middleware[0]({ ...context, next: nextMiddleware });
  });
}