import assert from 'node:assert/strict';
import test from 'node:test';

const nextConfig = require('../../next.config.js');

test('next dev ignores test compiler output to avoid route refresh interruptions', () => {
  assert.equal(typeof nextConfig.webpack, 'function');

  const config = nextConfig.webpack({ watchOptions: { ignored: ['**/node_modules/**'] } }, { dev: true });
  const ignored = config.watchOptions?.ignored;
  const ignoredList = Array.isArray(ignored) ? ignored : [ignored];

  assert.ok(ignoredList.includes('**/.tmp-test/**'));
});

test('next dev keeps watch ignored entries compatible with webpack schema', () => {
  const config = nextConfig.webpack({ watchOptions: { ignored: [/node_modules/] } }, { dev: true });
  const ignored = config.watchOptions?.ignored;
  const ignoredList = Array.isArray(ignored) ? ignored : [ignored];

  assert.deepEqual(ignoredList, ['**/.tmp-test/**']);
});

test('next config proxies API requests when the web container is exposed directly', async () => {
  const previousTarget = process.env.NEXT_API_PROXY_TARGET;
  process.env.NEXT_API_PROXY_TARGET = 'http://server:3001';

  try {
    const rewrites = await nextConfig.rewrites();
    assert.deepEqual(rewrites, [
      {
        source: '/api/v1/:path*',
        destination: 'http://server:3001/api/v1/:path*',
      },
    ]);
  } finally {
    if (previousTarget === undefined) {
      delete process.env.NEXT_API_PROXY_TARGET;
    } else {
      process.env.NEXT_API_PROXY_TARGET = previousTarget;
    }
  }
});

test('next config accepts API proxy targets that already include the API prefix', async () => {
  const previousTarget = process.env.NEXT_API_PROXY_TARGET;
  process.env.NEXT_API_PROXY_TARGET = 'http://server:3001/api/v1/';

  try {
    const rewrites = await nextConfig.rewrites();
    assert.deepEqual(rewrites, [
      {
        source: '/api/v1/:path*',
        destination: 'http://server:3001/api/v1/:path*',
      },
    ]);
  } finally {
    if (previousTarget === undefined) {
      delete process.env.NEXT_API_PROXY_TARGET;
    } else {
      process.env.NEXT_API_PROXY_TARGET = previousTarget;
    }
  }
});
