const NextFederationPlugin = require("@module-federation/nextjs-mf");

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  output: "standalone",
  transpilePackages: [
    "@edu/ui-tokens",
    "@edu/ui-components",
    "@edu/hooks",
  ],
  async rewrites() {
    const gatewayUrl = process.env.API_GATEWAY_URL || "http://localhost:8080";
    return [
      {
        source: "/api/admin/graphql",
        destination: `${gatewayUrl}/api/admin/graphql`,
      },
      {
        source: "/api/:path*",
        destination: `${gatewayUrl}/api/:path*`,
      },
    ];
  },
  webpack(config, { isServer }) {
    if (process.env.NEXT_PUBLIC_MF_ENABLED === "true") {
      config.plugins.push(
        new NextFederationPlugin({
          name: "admin_app",
          filename: "static/chunks/remoteEntry.js",
          exposes: {
            "./AdminApp": "./src/app/admin-app.tsx",
          },
          remotes: {
            teacher: `teacher_app@http://localhost:4000/_next/static/${isServer ? "ssr" : "chunks"}/remoteEntry.js`,
          },
          shared: {
            react: { singleton: true, requiredVersion: "^18.3.0" },
            "react-dom": { singleton: true, requiredVersion: "^18.3.0" },
            urql: { singleton: true },
            graphql: { singleton: true },
            "@edu/ui-tokens": { singleton: true },
            "@edu/ui-components": { singleton: true },
            "@edu/hooks": { singleton: true },
          },
          extraOptions: { exposePages: false },
        }),
      );
    }
    return config;
  },
};

module.exports = nextConfig;
