import type { NextConfig } from "next";

const isDev = process.env.NODE_ENV === "development";

/*
 * The API origin the browser talks to, from the same variable and fallback as
 * `src/lib/api/config.ts`. The CSP `connect-src` and the preconnect hint must
 * follow it: a hard-coded host blocks every API call (CSP violation, console
 * only) as soon as a build points at another backend. Like every
 * `NEXT_PUBLIC_*` value, it is fixed when `next build` runs.
 */
function apiOrigin(): string {
  const configured = process.env.NEXT_PUBLIC_BACKEND_URL?.trim() || "https://portal.fursa.raiyan.cc/api";
  try {
    return new URL(configured).origin;
  } catch {
    throw new Error(`NEXT_PUBLIC_BACKEND_URL is not an absolute URL: "${configured}"`);
  }
}
const API_ORIGIN = apiOrigin();

const nextConfig: NextConfig = {
  output: "standalone",
  // No `x-powered-by: Next.js` on every response: it only tells a scanner
  // which framework (and exploit list) to try. Security headers are set below.
  poweredByHeader: false,
  async redirects() {
    return [
      {
        source: "/learn-and-share-list",
        destination: "/development-opportunities-list",
        permanent: true,
      },
    ];
  },
  images: {
    unoptimized: true,
    remotePatterns: [
      {
        protocol: "https",
        hostname: "**",
      },
      {
        protocol: "http",
        hostname: "**",
      },

    ],
    // Next.js 16 requires an explicit qualities allowlist
    qualities: [25, 50, 75, 85, 100],
    formats: ["image/avif", "image/webp"],
    minimumCacheTTL: 86400, // 24 hours
  },

  // Strip all Moment.js locale data (~238 KB removed from bundle).
  // The app only needs English; locale strings are not used.
  webpack(config, { webpack }) {
    config.plugins.push(
      new webpack.IgnorePlugin({
        resourceRegExp: /^\.\/locale$/,
        contextRegExp: /moment$/,
      })
    );
    return config;
  },

  // Tree-shake large icon libraries so only used icons are bundled.
  experimental: {
    optimizePackageImports: ["lucide-react"],
  },

  async headers() {
    const securityHeaders = [
      {
        key: "X-Content-Type-Options",
        value: "nosniff",
      },
      {
        key: "Referrer-Policy",
        value: "strict-origin-when-cross-origin",
      },
      {
        key: "Permissions-Policy",
        // camera: the QR attendance scanner (getUserMedia). geolocation: the
        // location-checked scan (BE-101) and the map picker. Both same-origin only.
        value: "camera=(self), microphone=(), geolocation=(self), payment=()",
      },
      {
        key: "X-Frame-Options",
        value: "SAMEORIGIN",
      },
      {
        key: "Cross-Origin-Opener-Policy",
        value: "same-origin-allow-popups",
      },
      {
        key: "Cross-Origin-Resource-Policy",
        value: "cross-origin",
      },
      // HSTS: only meaningful over HTTPS; set a conservative max-age
      // Do NOT set this in dev (it would lock localhost to HTTPS)
      ...(!isDev
        ? [
          {
            key: "Strict-Transport-Security",
            value: "max-age=63072000; includeSubDomains; preload",
          },
        ]
        : []),
      {
        // Build CSP from the project's known domains.
        // unsafe-inline is required for Tailwind/inline styles; eval is avoided.
        // Third-party: Google OAuth, Google Maps, Google Fonts, Fursa API
        key: "Content-Security-Policy",
        value: [
          "default-src 'self'",
          // Scripts: self + Google OAuth/Maps + unsafe-eval in development for debugger/HMR
          `script-src 'self' 'unsafe-inline' ${
            isDev ? "'unsafe-eval'" : ""
          } https://accounts.google.com https://apis.google.com https://maps.googleapis.com https://www.gstatic.com`,
          // Styles: self + inline (Tailwind, third-party components) + Google Fonts
          // + the stylesheet Google Identity Services' Sign-in button loads.
          "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://accounts.google.com/gsi/style",
          // Images: self + data URIs + all https for API images
          "img-src 'self' data: blob: https:",
          // Fonts: self + Google Fonts CDN
          "font-src 'self' https://fonts.gstatic.com",
          // Connections: self + backend API + Google services + OSM Nominatim (location map picker geocoding)
          `connect-src 'self' ${API_ORIGIN} https://accounts.google.com https://maps.googleapis.com https://nominatim.openstreetmap.org`,
          // Frames: Google OAuth popup + the GIS Sign-in button iframe (/gsi/)
          // + API storage: a legacy HTML certificate is previewed in an iframe
          // (ProfileCertificatesGrid), which `frame-src` alone used to block.
          `frame-src https://accounts.google.com ${API_ORIGIN}`,
          // Media
          "media-src 'self' blob:",
          // Object: none
          "object-src 'none'",
          // Base URI: self only
          "base-uri 'self'",
          // Form action: self only
          "form-action 'self'",
          // frame-ancestors replaces X-Frame-Options in modern browsers
          "frame-ancestors 'self'",
        ].join("; "),
      },
    ];

    return [
      {
        source: "/(.*)",
        headers: [
          ...securityHeaders,
          // Preconnect to the API origin — browser opens TCP before first fetch
          {
            key: "Link",
            value: `<${API_ORIGIN}>; rel=preconnect, <${API_ORIGIN}>; rel=dns-prefetch`,
          },
        ],
      },
    ];
  },

  turbopack: {},
};

export default nextConfig;
