import type { NextConfig } from "next";

/**
 * Security headers (Phase 6 audit).
 * - CSP frame-src mirrors ALLOWED_EMBED_DOMAINS (evaluated at server start;
 *   restart after changing the allowlist). No arbitrary framing otherwise.
 * - Clickjacking: frame-ancestors 'self' + X-Frame-Options SAMEORIGIN.
 * - Admin routes carry X-Robots-Tag noindex (plus metadata robots).
 * NOTE: script/style 'unsafe-inline' is required by Next.js hydration and
 * Tailwind; no custom inline scripts are added by the app itself.
 */
function embedHosts(): string[] {
  const raw = process.env.ALLOWED_EMBED_DOMAINS ?? "";
  const hosts = raw
    .split(",")
    .map((s) => s.trim().toLowerCase().replace(/^\.+/, ""))
    .filter(Boolean);
  return [...new Set(hosts)];
}

function contentSecurityPolicy(): string {
  const hosts = embedHosts();
  const frameSrc = ["'self'", ...hosts.map((h) => `https://${h}`)].join(" ");
  const scriptSrc =
    process.env.NODE_ENV === "development"
      ? "'self' 'unsafe-inline' 'unsafe-eval'"
      : "'self' 'unsafe-inline'";
  return [
    "default-src 'self'",
    `script-src ${scriptSrc}`,
    "style-src 'self' 'unsafe-inline'",
    "img-src 'self' data: https:",
    "font-src 'self' data:",
    "connect-src 'self'",
    `frame-src ${frameSrc}`,
    "frame-ancestors 'self'",
    "form-action 'self'",
    "base-uri 'self'",
    "object-src 'none'",
  ].join("; ");
}

const nextConfig: NextConfig = {
  poweredByHeader: false,
  async headers() {
    const csp = contentSecurityPolicy();
    return [
      {
        source: "/:path*",
        headers: [
          { key: "Content-Security-Policy", value: csp },
          { key: "X-Frame-Options", value: "SAMEORIGIN" },
          { key: "X-Content-Type-Options", value: "nosniff" },
          {
            key: "Referrer-Policy",
            value: "strict-origin-when-cross-origin",
          },
          {
            key: "Permissions-Policy",
            value: "camera=(), microphone=(), geolocation=()",
          },
          {
            key: "Strict-Transport-Security",
            value: "max-age=31536000; includeSubDomains",
          },
        ],
      },
      {
        source: "/admin/:path*",
        headers: [{ key: "X-Robots-Tag", value: "noindex, nofollow" }],
      },
    ];
  },
};

export default nextConfig;
