import path from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const workspaceRoot = path.resolve(__dirname, "..", "..");
const domainDist = path.join(workspaceRoot, "packages/domain/dist");

// BFF URL for development API proxying
const BFF_URL = process.env.BFF_URL || "http://localhost:4000";
const isDev = process.env.NODE_ENV === "development";
const directApiBase = process.env.NEXT_PUBLIC_API_BASE;
const useDirectApiBase = Boolean(directApiBase && directApiBase.trim().startsWith("http"));

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: process.env.NODE_ENV === "production" ? "standalone" : undefined,

  // Required for monorepo workspace packages to be bundled correctly
  transpilePackages: ["@customer-portal/domain"],

  turbopack: {
    resolveAlias: {
      "@customer-portal/domain": domainDist,
    },
  },

  webpack(config, { dev }) {
    config.resolve.alias = {
      ...config.resolve.alias,
      "@customer-portal/domain": domainDist,
    };

    if (dev) {
      config.watchOptions = {
        ...config.watchOptions,
        // Poll-based watching is more reliable on WSL2 where inotify can miss events
        poll: 1000,
        aggregateTimeout: 300,
        ignored: ["**/node_modules/!(@@customer-portal)/**"],
      };
      // Only exclude the domain dist from managed paths so webpack detects domain rebuilds
      // without nuking the entire resolution cache (which causes crash loops)
      config.snapshot = {
        ...config.snapshot,
        managedPaths: [/[\\/]node_modules[\\/](?!@customer-portal[\\/])/],
      };
    }

    return config;
  },

  env: {
    // Default: same-origin (dev rewrites or prod nginx proxy).
    // Optional: set NEXT_PUBLIC_API_BASE (e.g. http://localhost:4000) to bypass Next rewrites and call the BFF directly via CORS.
    NEXT_PUBLIC_API_BASE: process.env.NEXT_PUBLIC_API_BASE ?? "",
    NEXT_PUBLIC_APP_NAME: process.env.NEXT_PUBLIC_APP_NAME,
    NEXT_PUBLIC_APP_VERSION: process.env.NEXT_PUBLIC_APP_VERSION,
  },

  // Proxy API requests to BFF in development
  async rewrites() {
    if (!isDev) return [];
    // If NEXT_PUBLIC_API_BASE is set, the app will call the BFF directly via CORS.
    // Avoid Next's internal dev proxy path (which can emit Node deprecation warnings).
    if (useDirectApiBase) return [];
    return [
      {
        source: "/api/:path*",
        destination: `${BFF_URL}/api/:path*`,
      },
    ];
  },

  compiler: {
    removeConsole: process.env.NODE_ENV === "production",
  },

  experimental: {
    optimizePackageImports: ["@heroicons/react", "@tanstack/react-query"],
  },

  typescript: { ignoreBuildErrors: false },
};

// Only load bundle analyzer when explicitly requested
let exportedConfig = nextConfig;

if (process.env.ANALYZE === "true") {
  const bundleAnalyzer = (await import("@next/bundle-analyzer")).default;
  exportedConfig = bundleAnalyzer({ enabled: true })(nextConfig);
}

export default exportedConfig;
