import {NextRequest, NextResponse} from "next/server";

export function middleware(request: NextRequest) {
	const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
	const cspHeader = `
    default-src 'self' *.stripe.com;
    script-src 'self' 'nonce-${nonce}' *.stripe.com;
    style-src 'self' 'nonce-${nonce}' *.stripe.com;
    img-src 'self' blob: data: *.stripe.com;
    font-src 'self' *.stripe.com;
    object-src 'none' *.stripe.com;
    base-uri 'self' *.stripe.com;
    form-action 'self' *.stripe.com;
    frame-ancestors 'none' *.stripe.com;
    block-all-mixed-content;
    upgrade-insecure-requests;
`;

	const requestHeaders = new Headers(request.headers);

	// Setting request headers
	requestHeaders.set("x-nonce", nonce);
	requestHeaders.set(
		"Content-Security-Policy",
		// Replace newline characters and spaces
		cspHeader.replace(/\s{2,}/g, " ").trim(),
	);

	return NextResponse.next({
		headers: requestHeaders,
		request: {
			headers: requestHeaders,
		},
	});
}

export const config = {
	matcher: [
		/*
		 * Match all request paths except for the ones starting with:
		 * - api (API routes)
		 * - _next/static (static files)
		 * - _next/image (image optimization files)
		 * - favicon.ico (favicon file)
		 */
		{
			source: "/((?!api|_next/static|_next/image|favicon.ico).*)",
			missing: [
				{type: "header", key: "next-router-prefetch"},
				{type: "header", key: "purpose", value: "prefetch"},
			],
		},
	],
};
