import assert from 'node:assert/strict';
import { test } from 'node:test';
import { codeToHtml } from '../src/lib/code.ts';
import { mentionQueryAt, mentionedUserIds, rankPeople, resolveMentions } from '../src/lib/mentions.ts';

const alice = { user_id: '@alice:example.org', name: 'Alice Liddell', avatar: null };
const bob = { user_id: '@bob:example.org', name: 'Bob', avatar: null };
const carol = { user_id: '@carol:example.org', name: 'Carol', avatar: null };

test('finds the query under the caret only at a word start', () => {
  assert.deepEqual(mentionQueryAt('hi @al', 6), { start: 3, query: 'al' });
  assert.deepEqual(mentionQueryAt('@', 1), { start: 0, query: '' });
  assert.equal(mentionQueryAt('me@al', 5), null);
  assert.equal(mentionQueryAt('@al ice', 7), null);
});

test('ranks by name and id, skipping yourself', () => {
  assert.deepEqual(rankPeople([alice, bob, carol], 'lid', null), [alice]);
  assert.deepEqual(rankPeople([alice, bob, carol], 'bob:ex', null), [bob]);
  assert.deepEqual(rankPeople([alice, bob, carol], '', '@bob:example.org'), [alice, carol]);
});

test('keeps picked names still in the body and typed matrix ids', () => {
  const picked = [
    { user_id: alice.user_id, text: alice.name },
    { user_id: bob.user_id, text: bob.name }
  ];
  const mentions = resolveMentions('Alice Liddell and @carol:example.org', picked);
  assert.deepEqual(mentionedUserIds(mentions), ['@alice:example.org', '@carol:example.org']);
});

test('links mentions outside code', () => {
  const mentions = [{ user_id: '@a<b:example.org', text: 'A<B' }];
  assert.equal(
    codeToHtml('hey A<B `A<B`', mentions),
    'hey <a href="https://matrix.to/#/@a&lt;b:example.org">A&lt;B</a> <code>A&lt;B</code>'
  );
  assert.equal(codeToHtml('nobody here', mentions), null);
});
