import { CONTINUE_PAGE_MIDDLEWARE, matchPageMiddlewareTarget } from "@open-mercato/shared/modules/middleware/page";
import { applyPageGuardOverridesToEntries } from "@open-mercato/shared/modules/overrides";
import { createLogger } from "../logger/index.js";
const logger = createLogger("shared").child({ component: "middleware" });
const DEFAULT_PRIORITY = 100;
function shouldRunMiddleware(middleware, mode, pathname) {
  if (middleware.mode && middleware.mode !== mode) return false;
  return matchPageMiddlewareTarget(pathname, middleware.target);
}
function compareMiddleware(a, b) {
  const priorityDiff = (a.priority ?? DEFAULT_PRIORITY) - (b.priority ?? DEFAULT_PRIORITY);
  if (priorityDiff !== 0) return priorityDiff;
  return a.id.localeCompare(b.id);
}
function flattenAndSortMiddleware(entries, mode, pathname) {
  return applyPageGuardOverridesToEntries(entries).flatMap((entry) => entry.middleware).filter((middleware) => shouldRunMiddleware(middleware, mode, pathname)).sort(compareMiddleware);
}
async function executePageMiddleware(args) {
  const { entries, context, onError } = args;
  const matchedMiddleware = flattenAndSortMiddleware(entries, context.mode, context.pathname);
  for (const middleware of matchedMiddleware) {
    try {
      const result = await middleware.run(context);
      if (result.action === "redirect") return result;
    } catch (error) {
      if (onError) {
        onError(error, { id: middleware.id, priority: middleware.priority });
      } else {
        logger.error("Page middleware execution failed", { id: middleware.id, err: error });
      }
      throw error;
    }
  }
  return CONTINUE_PAGE_MIDDLEWARE;
}
async function resolvePageMiddlewareRedirect(args) {
  const result = await executePageMiddleware(args);
  if (result.action !== "redirect") return null;
  return result.location;
}
export {
  executePageMiddleware,
  resolvePageMiddlewareRedirect
};
//# sourceMappingURL=page-executor.js.map
