import assert from 'node:assert/strict';
import { describe, it } from 'node:test';

import {
  assertSafeSPMIdentifier,
  isSafeSPMIdentifier,
  parseLinkedFrameworks,
} from './SPMIdentifier';

describe('isSafeSPMIdentifier', () => {
  const valid = [
    'SDWebImage',
    'lottie-spm',
    'react-native-screens',
    'Alamofire',
    'swift-protobuf',
    'Foo_Bar',
    'foo.bar',
    'a',
    'A1',
    '_underscore',
    'name+plus',
    'a'.repeat(128),
  ];
  for (const value of valid) {
    it(`accepts ${JSON.stringify(value)}`, () => {
      assert.equal(isSafeSPMIdentifier(value), true);
    });
  }

  const invalid: [string, unknown][] = [
    ['empty string', ''],
    ['leading dot', '.hidden'],
    ['leading dash', '-flag'],
    ['leading plus', '+plus'],
    ['parent traversal', '..'],
    ['traversal segment', '../escape'],
    ['embedded traversal', 'foo..bar'],
    ['forward slash', 'a/b'],
    ['backslash', 'a\\b'],
    ['NUL byte', 'a b'],
    ['space', 'a b'],
    ['tab', 'a\tb'],
    ['newline', 'a\nb'],
    ['double quote', 'a"b'],
    ['single quote', "a'b"],
    ['backtick', 'a`b'],
    ['dollar sign', 'a$b'],
    ['parenthesis', 'a(b'],
    ['semicolon', 'a;b'],
    ['ampersand', 'a&b'],
    ['pipe', 'a|b'],
    ['glob star', 'a*b'],
    ['glob question', 'a?b'],
    ['bracket', 'a[b'],
    ['brace', 'a{b'],
    ['too long', 'a'.repeat(129)],
    ['non-string number', 42],
    ['null', null],
    ['undefined', undefined],
    ['object', {}],
  ];
  for (const [label, value] of invalid) {
    it(`rejects ${label}`, () => {
      assert.equal(isSafeSPMIdentifier(value), false);
    });
  }
});

describe('assertSafeSPMIdentifier', () => {
  it('returns void for safe values', () => {
    assertSafeSPMIdentifier('SDWebImage', 'productName');
  });

  it('throws with the field name and the offending value for unsafe strings', () => {
    assert.throws(
      () => assertSafeSPMIdentifier('../escape', 'productName'),
      (err: Error) => err.message.includes('productName') && err.message.includes('"../escape"')
    );
  });

  it('throws for non-string inputs without leaking raw objects into the message', () => {
    assert.throws(
      () => assertSafeSPMIdentifier(42, 'packageName'),
      (err: Error) => err.message.includes('packageName') && err.message.includes('number')
    );
  });
});

describe('parseLinkedFrameworks', () => {
  it('reads a missing value as no frameworks', () => {
    assert.deepEqual(parseLinkedFrameworks(undefined, 'FixtureTarget'), []);
  });

  it('accepts a list of framework names', () => {
    assert.deepEqual(parseLinkedFrameworks([], 'FixtureTarget'), []);
    assert.deepEqual(
      parseLinkedFrameworks(['UIKit', 'AVFoundation', '_Private'], 'FixtureTarget'),
      ['UIKit', 'AVFoundation', '_Private']
    );
  });

  const malformed: [string, unknown, unknown][] = [
    ['an object', { common: ['UIKit'] }, { common: ['UIKit'] }],
    ['a bare string', 'UIKit', 'UIKit'],
    ['null', null, null],
    ['an empty string', '', ''],
    ['zero', 0, 0],
    ['false', false, false],
    ['a non-string entry', [1], 1],
    ['an empty entry', [''], ''],
    ['a dotted module path', ['Foo.Bar'], 'Foo.Bar'],
    ['an entry that breaks out of a Swift string', ['UIKit"); evil'], 'UIKit"); evil'],
    ['an entry starting with a digit', ['1UIKit'], '1UIKit'],
  ];

  for (const [description, value, offender] of malformed) {
    it(`rejects ${description} with a diagnostic naming the target and the value`, () => {
      assert.throws(
        () => parseLinkedFrameworks(value, 'FixtureTarget'),
        (error: Error) => {
          assert.ok(!(error instanceof TypeError), `Expected a diagnostic, got ${error.stack}`);
          assert.ok(
            error.message.startsWith(
              `Cannot read "linkedFrameworks" for target "FixtureTarget": ${JSON.stringify(offender)}`
            ),
            error.message
          );
          assert.match(error.message, /"linkedFrameworks": \["UIKit", "AVFoundation"\]/);
          return true;
        }
      );
    });
  }
});
