import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { generateNonce } from "../nonce";
import { buildSecurityHeaders } from "../build-security-headers";

export function withSecurityHeaders(request: NextRequest): NextResponse {
  const nonce = generateNonce();
  const mode = process.env.NODE_ENV === "production" ? "prod" : "dev";
  const secHeaders = buildSecurityHeaders({ mode, nonce });

  const requestHeaders = new Headers(request.headers);
  requestHeaders.set("x-nonce", nonce);

  const response = NextResponse.next({
    request: { headers: requestHeaders },
  });

  for (const [name, value] of Object.entries(secHeaders)) {
    response.headers.set(name, value);
  }
  response.headers.set("x-nonce", nonce);

  return response;
}
