import { type NextRequest, NextResponse } from "next/server";
import { authProxy } from "~/proxies/auth";
import { apisProxy } from "./proxies/api";
import { pswChangeProxy } from "./proxies/psw_change";
import { TestRedirectProxy } from "./proxies/test_redirect";

export async function proxy(request: NextRequest) {
	//console.log("Proxy triggered for:", request.nextUrl.pathname);

	return await chainProxies(request, [
		TestRedirectProxy,
		//updaterProxy,
		apisProxy,
		pswChangeProxy,
		authProxy,
	]);
}

export const config = {
	matcher: [
		"/storage-api/:path*",
		{
			source: "/",
		},
		{
			missing: [
				{ key: "next-router-prefetch", type: "header" },
				{ key: "purpose", type: "header", value: "prefetch" },
			],
			source:
				"/((?!api/trpc|api/tiles|api/auth|_next/static|_next/image|screenshots|site.webmanifest|favicon.ico|favicon|sitemap.xml|robots.txt|login).*)",
		},
	],
};

// Type for Proxy functions
export type ProxyFn = (
	request: NextRequest,
) => Promise<NextResponse | null | undefined> | NextResponse | null | undefined;

// Helper to chain proxies in order
async function chainProxies(
	request: NextRequest,
	proxies: ProxyFn[],
): Promise<NextResponse> {
	for (const proxy of proxies) {
		const result = await proxy(request);

		// If proxy returned a response, short-circuit
		if (result) {
			return result;
		}
		// Otherwise, continue to next proxy
	}

	// All proxies passed, continue to the app
	return NextResponse.next();
}
