/** @type {import('next').NextConfig} */
const TEST_OUTPUT_GLOB = '**/.tmp-test/**';

function toIgnoredList(ignored) {
  if (!ignored) return [];
  const entries = Array.isArray(ignored) ? ignored : [ignored];
  return entries.filter((entry) => typeof entry === 'string' && entry.length > 0);
}

function toApiProxyDestination(target) {
  const cleanTarget = target.trim().replace(/\/+$/, '');
  if (!cleanTarget) return null;
  const apiBase = cleanTarget.endsWith('/api/v1') ? cleanTarget : `${cleanTarget}/api/v1`;
  return `${apiBase}/:path*`;
}

const nextConfig = {
  transpilePackages: ['@ftb/shared'],
  async rewrites() {
    const destination = toApiProxyDestination(process.env.NEXT_API_PROXY_TARGET || '');
    if (!destination) return [];
    return [
      {
        source: '/api/v1/:path*',
        destination,
      },
    ];
  },
  webpack(config, { dev }) {
    if (dev) {
      const ignored = toIgnoredList(config.watchOptions?.ignored);
      config.watchOptions = {
        ...config.watchOptions,
        ignored: ignored.includes(TEST_OUTPUT_GLOB) ? ignored : [...ignored, TEST_OUTPUT_GLOB],
      };
    }
    return config;
  },
};

module.exports = nextConfig;
