/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  output: 'standalone',
  async rewrites() {
    // API 路由模式:
    // 1. 设置了 API_GATEWAY_URL -> 通过 Kong 网关代理 (适用于前端与后端不在同一 Docker 网络)
    // 2. 未设置 API_GATEWAY_URL -> 直连各后端服务 (适用于同一 Docker 网络, 推荐 standalone 模式)
    const apiGatewayUrl = process.env.API_GATEWAY_URL || '';
    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';
    const snapshotServiceUrl = process.env.SNAPSHOT_SERVICE_URL || 'http://localhost:3199';

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

    if (apiGatewayUrl) {
      // 通过 Kong 网关: 所有请求经 Kong 路由分发到各服务
      return [
        {
          source: '/api/snapshots/:path*',
          destination: `${snapshotServiceUrl}/api/v1/:path*`,
        },
        {
          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 {
      // 直连各服务: 前端与后端在同一 Docker 网络内直接通信
      return [
        {
          source: '/api/snapshots/:path*',
          destination: `${snapshotServiceUrl}/api/v1/:path*`,
        },
        {
          source: '/api/trading/:path*',
          destination: `${cleanTradingUrl}/api/v2/:path*`,
        },
        {
          // mining-service 的 controller 有 mining/ 前缀, 需保留
          source: '/api/mining/:path*',
          destination: `${cleanMiningUrl}/api/v2/mining/:path*`,
        },
        {
          source: '/api/:path*',
          destination: `${cleanMiningAdminUrl}/api/v2/:path*`,
        },
      ];
    }
  },
};

module.exports = nextConfig;
