import assert from 'node:assert/strict';
import { test } from 'node:test';
import { formatBody } from '../src/lib/markdown.ts';
import { mentionQueryAt, mentionedUserIds, rankPeople, resolveMentions, stripMarkdownPills } from '../src/lib/mentions.ts';
import { findUrls } from '../src/lib/urls.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(
    formatBody('hey A<B `A<B`', mentions, true),
    '<p>hey <a href="https://matrix.to/#/@a&lt;b:example.org">A&lt;B</a> <code>A&lt;B</code></p>'
  );
  assert.equal(formatBody('hey A<B', mentions, false), 'hey <a href="https://matrix.to/#/@a&lt;b:example.org">A&lt;B</a>');
  assert.equal(formatBody('nobody here', mentions, true), null);
});

test('markdown pills in the plain body become names', () => {
  const body = 'Good Morning [lillis](https://matrix.to/#/@lillis:matrix.org),\nhi';
  assert.deepEqual(stripMarkdownPills(body), {
    text: 'Good Morning lillis,\nhi',
    mentions: [{ user_id: '@lillis:matrix.org', text: 'lillis' }]
  });
  assert.deepEqual(stripMarkdownPills('[x](https://matrix.to/#/@%E0%A4%A)'), {
    text: '[x](https://matrix.to/#/@%E0%A4%A)',
    mentions: []
  });
});

test('matrix.to permalinks get no link card', () => {
  assert.deepEqual(
    findUrls('https://matrix.to/#/@lillis:matrix.org and https://example.org/a').map((u) => u.href),
    ['https://example.org/a']
  );
});
