import type { NextConfig } from "next";

const isProduction = process.env.NODE_ENV === "production";

// No third-party origins are used anywhere (fonts are self-hosted by next/font).
// Inline scripts/styles are needed by Next.js itself; a nonce-based policy can
// replace 'unsafe-inline' later if required. Dev mode needs eval, so the CSP
// is production-only.
const contentSecurityPolicy = [
  "default-src 'self'",
  "script-src 'self' 'unsafe-inline'",
  "style-src 'self' 'unsafe-inline'",
  "img-src 'self' data:",
  "font-src 'self'",
  "connect-src 'self'",
  "object-src 'none'",
  "base-uri 'self'",
  "form-action 'self'",
  "frame-ancestors 'none'",
].join("; ");

const nextConfig: NextConfig = {
  // Native/Node-only packages: load from node_modules instead of bundling.
  serverExternalPackages: ["@node-rs/argon2", "pg"],
  poweredByHeader: false,
  // Development only: the dev server refuses to serve /_next assets to any
  // hostname other than localhost, so colleagues opening http://<this machine's
  // LAN IP>:3000 would get the HTML but no scripts or styles. Allow the office
  // network range and Bonjour names (`<mac-name>.local`). Has no effect on
  // `next build` / `next start`.
  allowedDevOrigins: ["172.16.*.*", "192.168.*.*", "10.*.*.*", "*.local"],
  experimental: {
    // Sheet uploads for "Import Apps" (the import itself caps files at 4 MB).
    serverActions: { bodySizeLimit: "5mb" },
  },
  async headers() {
    return [
      {
        source: "/:path*",
        headers: [
          { key: "X-Frame-Options", value: "DENY" },
          { key: "X-Content-Type-Options", value: "nosniff" },
          { key: "Referrer-Policy", value: "same-origin" },
          { key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=()" },
          ...(isProduction
            ? [
                { key: "Content-Security-Policy", value: contentSecurityPolicy },
                // Ignored by browsers over plain HTTP, so harmless for local production runs.
                { key: "Strict-Transport-Security", value: "max-age=31536000; includeSubDomains" },
              ]
            : []),
        ],
      },
    ];
  },
};

export default nextConfig;
