import { generateNonce } from "../nonce";
import { buildSecurityHeaders } from "../build-security-headers";

export type TanstackSecurityHeadersResult = {
  nonce: string;
  headers: Record<string, string>;
};

/**
 * Generates a nonce and builds all six security headers plus x-nonce.
 * Intended for use inside a TanStack Start / Nitro server middleware:
 *   const { nonce, headers } = withSecurityHeaders();
 *   for (const [k, v] of Object.entries(headers)) setResponseHeader(event, k, v);
 *   event.node.req.headers["x-nonce"] = nonce; // forward for getNonce()
 */
export function withSecurityHeaders(): TanstackSecurityHeadersResult {
  const nonce = generateNonce();
  const mode = process.env.NODE_ENV === "production" ? "prod" : "dev";
  const secHeaders = buildSecurityHeaders({ mode, nonce });
  return {
    nonce,
    headers: { ...secHeaders, "x-nonce": nonce },
  };
}
