import type { NextConfig } from "next";
import createNextIntlPlugin from "next-intl/plugin";
import {
  APP_PAGE_HEADER_SOURCE,
  PAGE_CACHE_CONTROL,
} from "./lib/http-cache-policy";
import {
  getEnvRemoteImageDomains,
  getRemotePatterns,
} from "./lib/remote-image-domains";

const withNextIntl = createNextIntlPlugin("./lib/i18n/request.ts");

const nextConfig: NextConfig = {
  reactCompiler: true,
  skipTrailingSlashRedirect: true,
  experimental: {
    // Next's client-side Router Cache defaults to reusing a prefetched static
    // route for 300s. On a storefront that means a shopper who is already
    // browsing keeps seeing the pre-edit catalog for up to five minutes after
    // an admin publishes a product. 30s is the floor Next accepts here (0 is
    // rejected by config validation) and cuts that window by an order of
    // magnitude; the refetch is served by the ISR/`unstable_cache` layers, so
    // it costs a round trip, not a database query.
    staleTimes: {
      dynamic: 0,
      static: 30,
    },
  },
  outputFileTracingIncludes: {
    "/api/admin/ai-authoring/hero-banner": [
      "./node_modules/@fontsource/noto-sans/files/*.woff2",
      "./node_modules/@fontsource/noto-sans-bengali/files/*.woff2",
    ],
  },
  async headers() {
    return [
      // Stop browsers reusing storefront/admin documents without asking — see
      // lib/http-cache-policy.ts for why Next's default header let them.
      // Overriding Cache-Control here is the supported escape hatch:
      // `sendRenderResult` only applies Next's own value when the response does
      // not already carry one. Server-side caching is untouched; the ISR cache
      // and the `unstable_cache` getters still serve the render, and
      // lib/cache-invalidation.ts expires them on write.
      {
        source: APP_PAGE_HEADER_SOURCE,
        headers: [{ key: "Cache-Control", value: PAGE_CACHE_CONTROL }],
      },
      {
        // `APP_PAGE_HEADER_SOURCE` cannot match the bare root, which next-intl
        // redirects to the resolved locale.
        source: "/",
        headers: [{ key: "Cache-Control", value: PAGE_CACHE_CONTROL }],
      },
      {
        source: "/sw.js",
        headers: [
          {
            key: "Cache-Control",
            value: "no-store, max-age=0",
          },
        ],
      },
      {
        source: "/manifest.webmanifest",
        headers: [
          {
            key: "Cache-Control",
            value: "no-cache",
          },
        ],
      },
      {
        // Local-storage uploads (default path prefix). Keys embed a
        // timestamp + random suffix so they never change → cache forever.
        // The CSP sandbox neutralizes scripts in user-supplied SVGs, which
        // would otherwise run same-origin when opened directly.
        source: "/uploads/:path*",
        headers: [
          {
            key: "Cache-Control",
            value: "public, max-age=31536000, immutable",
          },
          {
            key: "X-Content-Type-Options",
            value: "nosniff",
          },
          {
            key: "Content-Security-Policy",
            value: "default-src 'none'; style-src 'unsafe-inline'; sandbox",
          },
        ],
      },
    ];
  },
  images: {
    // Single source of truth shared with AppImage's trusted-host check
    // (lib/remote-image-domains.ts) so the optimizer whitelist and the
    // client-side "can the optimizer load this?" decision never drift apart.
    // Env-configured custom storage domains (STORAGE_PUBLIC_URL etc.) are
    // appended so self-hosted CDN setups get optimized images too.
    remotePatterns: getRemotePatterns(getEnvRemoteImageDomains()),
  },
};

export default withNextIntl(nextConfig);
