/* test/publicBaseUrl.test.js
 *
 * Validates the P0 #1 fix: APP_URL / PUBLIC_BASE_URL fallback chain.
 */
'use strict';

const assert = require('assert');
const TESTS = [];
const test = (n, fn) => TESTS.push({ name: n, fn });

// Per-test isolation: require the module fresh each time by clearing cache
function loadFresh() {
  delete require.cache[require.resolve('../config/publicBaseUrl')];
  return require('../config/publicBaseUrl');
}

test('PUBLIC_BASE_URL wins', () => {
  process.env.PUBLIC_BASE_URL = 'https://primary.test';
  process.env.APP_URL = 'https://fallback.test';
  const { publicBaseUrl, resetCache } = loadFresh();
  resetCache();
  assert.strictEqual(publicBaseUrl(), 'https://primary.test');
});

test('APP_URL fallback', () => {
  delete process.env.PUBLIC_BASE_URL;
  process.env.APP_URL = 'https://fallback.test';
  const { publicBaseUrl, resetCache } = loadFresh();
  resetCache();
  assert.strictEqual(publicBaseUrl(), 'https://fallback.test');
});

test('dev fallback to localhost', () => {
  delete process.env.PUBLIC_BASE_URL;
  delete process.env.APP_URL;
  delete process.env.PORT;
  const { publicBaseUrl, resetCache } = loadFresh();
  resetCache();
  assert.strictEqual(publicBaseUrl(), 'http://localhost:3000');
});

test('trailing slash stripped', () => {
  process.env.PUBLIC_BASE_URL = 'https://x.test/';
  const { publicBaseUrl, resetCache } = loadFresh();
  resetCache();
  assert.strictEqual(publicBaseUrl(), 'https://x.test');
});

test('assertProductionEnv refuses to boot without PUBLIC_BASE_URL', () => {
  process.env.NODE_ENV = 'production';
  delete process.env.PUBLIC_BASE_URL;
  delete process.env.APP_URL;
  delete process.env.SESSION_SECRET;
  delete process.env.TRUST_PROXY;
  // Stub process.exit
  const realExit = process.exit;
  let exited = false;
  process.exit = (code) => { exited = true; throw new Error(`exit(${code})`); };
  delete require.cache[require.resolve('../config/assertProductionEnv')];
  const { assertProductionEnv } = require('../config/assertProductionEnv');
  try { assertProductionEnv(); } catch (_) { /* expected */ }
  process.exit = realExit;
  assert.strictEqual(exited, true, 'assertProductionEnv must call process.exit in production without env');
});

test('assertProductionEnv passes in dev', () => {
  process.env.NODE_ENV = 'development';
  delete require.cache[require.resolve('../config/assertProductionEnv')];
  const { assertProductionEnv } = require('../config/assertProductionEnv');
  assert.doesNotThrow(() => assertProductionEnv());
});

module.exports = TESTS;
