const test = require('node:test');
const assert = require('node:assert/strict');

const Logger = require('../src/helper/logger.js');

function withPatchedConsole(fn) {
  const original = {
    debug: console.debug,
    info: console.info,
    warn: console.warn,
    error: console.error,
  };

  const calls = [];
  console.debug = (...args) => calls.push(['debug', ...args]);
  console.info = (...args) => calls.push(['info', ...args]);
  console.warn = (...args) => calls.push(['warn', ...args]);
  console.error = (...args) => calls.push(['error', ...args]);

  try {
    fn(calls);
  } finally {
    console.debug = original.debug;
    console.info = original.info;
    console.warn = original.warn;
    console.error = original.error;
  }
}

test('respects log level threshold', () => {
  withPatchedConsole((calls) => {
    const logger = new Logger(true, 'warn', 'T');
    logger.debug('a');
    logger.info('b');
    logger.warn('c');
    logger.error('d');

    const levels = calls.map((c) => c[0]);
    assert.deepEqual(levels, ['warn', 'error']);
  });
});

test('toggleLogging disables output', () => {
  withPatchedConsole((calls) => {
    const logger = new Logger(true, 'debug', 'T');
    logger.toggleLogging();
    logger.debug('x');
    logger.error('y');
    assert.equal(calls.length, 0);
  });
});

test('setLogLevel updates to valid level', () => {
  const logger = new Logger(true, 'debug', 'T');
  logger.setLogLevel('error');
  assert.equal(logger.logLevel, 'error');
});

test('setLogLevel with invalid value should not throw', () => {
  withPatchedConsole(() => {
    const logger = new Logger(true, 'debug', 'T');
    assert.doesNotThrow(() => logger.setLogLevel('invalid-level'));
    assert.equal(logger.logLevel, 'debug');
  });
});
