import type { NextConfig } from "next";

const securityHeaders = [
  { key: "X-Content-Type-Options", value: "nosniff" },
  { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
  { key: "X-Frame-Options", value: "SAMEORIGIN" },
  { key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=(), interest-cohort=()" },
];

/** Allow optimizing images served from the S3 bucket's public URL, if configured. */
const s3Pattern = (() => {
  const raw = process.env.S3_PUBLIC_URL;
  if (!raw) return [];
  try {
    const u = new URL(raw);
    return [{ protocol: u.protocol.replace(":", "") as "https" | "http", hostname: u.hostname, port: u.port, pathname: "/**" }];
  } catch {
    return [];
  }
})();

const nextConfig: NextConfig = {
  cacheComponents: true,
  partialPrefetching: true,
  poweredByHeader: false,
  images: {
    remotePatterns: [{ protocol: "https", hostname: "images.unsplash.com", pathname: "/**" }, ...s3Pattern],
  },
  async redirects() {
    return [{ source: "/biogas-power-plants", destination: "/bio-enterprises", permanent: true }];
  },
  async headers() {
    return [
      { source: "/:path*", headers: securityHeaders },
      { source: "/admin/:path*", headers: [{ key: "X-Robots-Tag", value: "noindex, nofollow" }, { key: "Cache-Control", value: "no-store" }] },
    ];
  },
  turbopack: {
    rules: {
      "*.css": {
        loaders: ["@tailwindcss/turbopack"],
        as: "*.css",
      },
    },
  },
};

export default nextConfig;
