/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  output: 'standalone',
  async rewrites() {
    // 获取 API 基础 URL（Kong 网关地址）
    // 生产环境: https://rwaapi.szaiai.com
    // 开发环境: http://localhost:3023 (mining-admin-service)
    const apiGatewayUrl = process.env.API_GATEWAY_URL || 'https://rwaapi.szaiai.com';
    const miningAdminUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3023';
    const tradingServiceUrl = process.env.TRADING_SERVICE_URL || 'http://localhost:3022';
    const miningServiceUrl = process.env.MINING_SERVICE_URL || 'http://localhost:3021';

    // 检查是否是生产环境（使用 Kong 网关）
    const isProduction = process.env.NODE_ENV === 'production';

    // 移除末尾可能存在的路径避免重复
    const cleanMiningAdminUrl = miningAdminUrl.replace(/\/api\/v2.*$/, '');
    const cleanTradingUrl = tradingServiceUrl.replace(/\/api\/v2.*$/, '');
    const cleanMiningUrl = miningServiceUrl.replace(/\/api\/v2.*$/, '');

    if (isProduction) {
      // 生产环境：通过 Kong 网关
      // /api/trading/* -> Kong -> trading-service
      // /api/mining/* -> Kong -> mining-service
      // /api/* -> Kong -> mining-admin-service
      return [
        {
          source: '/api/trading/:path*',
          destination: `${apiGatewayUrl}/api/v2/trading/:path*`,
        },
        {
          source: '/api/mining/:path*',
          destination: `${apiGatewayUrl}/api/v2/mining/:path*`,
        },
        {
          source: '/api/:path*',
          destination: `${apiGatewayUrl}/api/v2/mining-admin/:path*`,
        },
      ];
    } else {
      // 开发环境：直连各服务
      return [
        {
          source: '/api/trading/:path*',
          destination: `${cleanTradingUrl}/api/v2/:path*`,
        },
        {
          source: '/api/mining/:path*',
          destination: `${cleanMiningUrl}/api/v2/:path*`,
        },
        {
          source: '/api/:path*',
          destination: `${cleanMiningAdminUrl}/api/v2/:path*`,
        },
      ];
    }
  },
};

module.exports = nextConfig;
