import { test } from 'node:test';
import assert from 'node:assert/strict';
import { isValidServerPattern, globToRegExp, matchesAnyGlob } from './serverAcl';

test('isValidServerPattern: accepts hostnames, IPs, and globs', () => {
  for (const v of [
    '*',
    '*.example.com',
    'matrix.org',
    '1.2.3.*',
    '10.0.0.?',
    '*.evil.*',
    '*bad*',
  ]) {
    assert.equal(isValidServerPattern(v), true, v);
  }
});

test('isValidServerPattern: rejects empty, malformed, and non-glob junk', () => {
  for (const v of ['', '   ', '.foo', 'foo.', 'a..b', '-', ':', 'under_score', 'a,b', 'a b']) {
    assert.equal(isValidServerPattern(v), false, v);
  }
});

test('globToRegExp: * = any run, ? = single char, other metachars escaped', () => {
  assert.equal(globToRegExp('*').test('anything.org'), true);
  assert.equal(globToRegExp('*.evil.com').test('a.evil.com'), true);
  assert.equal(globToRegExp('*.evil.com').test('evil.com'), false); // needs the leading label
  assert.equal(globToRegExp('1.2.3.?').test('1.2.3.4'), true);
  assert.equal(globToRegExp('1.2.3.?').test('1.2.3.45'), false);
  // The dot is a literal, not a regex wildcard.
  assert.equal(globToRegExp('a.b').test('axb'), false);
});

test('globToRegExp: case-insensitive (hostnames + Synapse IGNORECASE)', () => {
  assert.equal(globToRegExp('MATRIX.foo.org').test('matrix.foo.org'), true);
});

test('matchesAnyGlob: true if any glob matches (self-ban detection)', () => {
  assert.equal(matchesAnyGlob('lotusguild.org', ['*']), true);
  assert.equal(matchesAnyGlob('lotusguild.org', ['*.evil.com', 'lotus*.org']), true);
  assert.equal(matchesAnyGlob('lotusguild.org', ['*.evil.com']), false);
  assert.equal(matchesAnyGlob('lotusguild.org', []), false);
});
