import { type NextRequest, NextResponse } from "next/server";
import { authMiddleware } from "~/middlewares/auth";
import { apisMiddleware } from "./middlewares/api";
import { pswChangeMiddleware } from "./middlewares/psw_change";

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

	return await chainMiddlewares(request, [
		apisMiddleware,
		pswChangeMiddleware,
		authMiddleware,
	]);
}

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

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

// Helper to chain middlewares in order
async function chainMiddlewares(
	request: NextRequest,
	middlewares: MiddlewareFn[],
): Promise<NextResponse> {
	for (const middleware of middlewares) {
		const result = await middleware(request);

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

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