import { NextResponse } from "next/server";
import {
  MIDDLEWARE_REGISTRY
} from "@nextsparkjs/registries/middleware-registry";
import {
  THEME_REGISTRY
} from "@nextsparkjs/registries/theme-registry";
function hasThemeMiddleware(themeName) {
  var _a;
  return themeName in MIDDLEWARE_REGISTRY && ((_a = MIDDLEWARE_REGISTRY[themeName]) == null ? void 0 : _a.exists) === true;
}
async function executeThemeMiddleware(themeName, request, coreSession) {
  const entry = MIDDLEWARE_REGISTRY[themeName];
  if (!entry || !entry.exists) {
    return null;
  }
  try {
    return await entry.middleware(request, coreSession);
  } catch (error) {
    console.error(`Error executing middleware for theme '${themeName}':`, error);
    return null;
  }
}
function getThemeAppConfig(themeName) {
  var _a;
  return (_a = THEME_REGISTRY[themeName]) == null ? void 0 : _a.appConfig;
}
function redirectWithoutSession(request, targetPath = "/login") {
  const { pathname } = request.nextUrl;
  const loginUrl = new URL(targetPath, request.url);
  loginUrl.searchParams.set("callbackUrl", pathname);
  return NextResponse.redirect(loginUrl);
}
function redirectWithSession(request, targetPath = "/dashboard") {
  return NextResponse.redirect(new URL(targetPath, request.url));
}
function addUserHeaders(request, sessionUser) {
  const requestHeaders = new Headers(request.headers);
  if (sessionUser == null ? void 0 : sessionUser.id) {
    requestHeaders.set("x-user-id", sessionUser.id);
  }
  if (sessionUser == null ? void 0 : sessionUser.email) {
    requestHeaders.set("x-user-email", sessionUser.email);
  }
  requestHeaders.set("x-pathname", request.nextUrl.pathname);
  return NextResponse.next({
    request: {
      headers: requestHeaders
    }
  });
}
export {
  addUserHeaders,
  executeThemeMiddleware,
  getThemeAppConfig,
  hasThemeMiddleware,
  redirectWithSession,
  redirectWithoutSession
};
