/** @type {import("next").NextConfig} */
const nextConfig = {
  output: "standalone",
  outputFileTracingIncludes: {
    "/*": ["./.next/static/**/*", "./public/**/*"],
  },
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "cdn.sanity.io",
        port: "",
      },
      {
        protocol: "https",
        hostname: "lh3.googleusercontent.com",
        port: "",
      },
      {
        protocol: "https",
        hostname: "avatars.githubusercontent.com",
        port: "",
      },
      {
        protocol: "https",
        hostname: "pub-b7fd9c30cdbf439183b75041f5f71b92.r2.dev",
        port: "",
      },
      {
        protocol: "https",
        hostname: "admin.opplenz.com",
        port: "",
      },
    ],
  },
  async rewrites() {
    // The same build is deployed to two domains, each with its own backend:
    //   - test:       opplenz.com  -> https://admin.opplenz.com/admin/v1
    //   - production: opplens.com  -> https://admin.opplens.com/admin/v1
    // Routing is host-based so neither deploy needs a custom env. A
    // `BACKEND_API_BASE_URL` env var (if set) overrides both — handy for local
    // dev pointing at e.g. http://localhost:8080/admin/v1.
    // ! ⚠️ IMPORTANT: Adding BACKEND_API_BASE_URL to env file will break the multi-domain feature.
    const override = process.env.BACKEND_API_BASE_URL;
    if (override) {
      return [
        {
          source: "/api/proxy/:path*",
          destination: `${override}/:path*`,
        },
      ];
    }

    return [
      // Production: any opplens.com host (apex or subdomain like www.).
      {
        source: "/api/proxy/:path*",
        has: [{ type: "host", value: "(.*\\.)?opplens\\.com" }],
        destination: "https://admin.opplens.com/admin/v1/:path*",
      },
      // Default (test opplenz.com + local dev).
      {
        source: "/api/proxy/:path*",
        destination: "https://admin.opplenz.com/admin/v1/:path*",
      },
    ];
  },
};
export default nextConfig;
