import { NextResponse } from "next/server";

//#region src/proxy/multipleProxies.ts
/**
* Utility to combine multiple Next.js proxies into one.
*
* It executes proxies in order, merges headers, and correctly handles
* redirects and rewrites.
*
* @example
* import { multipleProxies, intlayerProxy } from "next-intlayer/proxy";
* import { NextResponse } from "next/server";
*
* const authMiddleware = (req: NextRequest) => {
*   if (!req.cookies.get("token")) {
*     return NextResponse.redirect(new URL("/login", req.url));
*   }
*   return NextResponse.next();
* };
*
* export default multipleProxies([
*   intlayerProxy,
*   authMiddleware,
* ]);
*
* @param proxies - An array of proxy functions to execute in order.
* @returns A single proxy function that runs all provided proxies.
*/
const multipleProxies = (proxies) => async (req, event, response) => {
	const proxyHeader = [];
	for (const proxy of proxies) {
		const result = await proxy(req, event, response);
		if (!result.ok) return result;
		proxyHeader.push(result.headers);
	}
	const mergedHeaders = new Headers();
	const transmittedHeaders = new Headers();
	proxyHeader.forEach((header) => {
		for (const [key, value] of header.entries()) {
			mergedHeaders.append(key, value);
			if (key.startsWith("x-middleware-request-")) {
				const fixedKey = key.replace("x-middleware-request-", "");
				transmittedHeaders.append(fixedKey, value);
			}
		}
	});
	const redirect = mergedHeaders.get("x-middleware-request-redirect");
	if (redirect) return NextResponse.redirect(new URL(redirect, req.url), { status: 307 });
	const rewrite = mergedHeaders.get("x-middleware-rewrite");
	if (rewrite) return NextResponse.rewrite(new URL(rewrite, req.url), { request: { headers: transmittedHeaders } });
	return NextResponse.next({ request: { headers: transmittedHeaders } });
};

//#endregion
export { multipleProxies };
//# sourceMappingURL=multipleProxies.mjs.map