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

// This module uses atomWithStorage(..., { getOnInit: true }), so it reads
// `localStorage` the moment it's evaluated. node has none, so install a no-op
// mock, then import dynamically (a static import would be hoisted above the
// mock assignment and evaluate the module too early).
(globalThis as { localStorage?: unknown }).localStorage = {
  getItem: () => null,
  setItem: () => undefined,
  removeItem: () => undefined,
};

const { addRecentForwardTarget } = await import('./recentForwardTargets');

test('addRecentForwardTarget prepends a new roomId', () => {
  assert.deepEqual(addRecentForwardTarget(['!a', '!b'], '!c'), ['!c', '!a', '!b']);
});

test('addRecentForwardTarget dedupes and moves the roomId to the front', () => {
  assert.deepEqual(addRecentForwardTarget(['!a', '!b', '!c'], '!b'), ['!b', '!a', '!c']);
});

test('addRecentForwardTarget ignores an empty roomId', () => {
  assert.deepEqual(addRecentForwardTarget(['!a', '!b'], ''), ['!a', '!b']);
});

test('addRecentForwardTarget caps the list at 8 entries, dropping the oldest', () => {
  const eight = Array.from({ length: 8 }, (_, i) => `!r${i}`);
  const result = addRecentForwardTarget(eight, '!new');
  assert.equal(result.length, 8);
  assert.equal(result[0], '!new');
  // the oldest entry (last) is dropped
  assert.equal(result.includes('!r7'), false);
  assert.deepEqual(result.slice(1), eight.slice(0, 7));
});

test('addRecentForwardTarget does not mutate its input', () => {
  const input = ['!a', '!b'];
  const before = [...input];
  addRecentForwardTarget(input, '!c');
  assert.deepEqual(input, before);
});

test('addRecentForwardTarget on an empty history returns a single-element list', () => {
  assert.deepEqual(addRecentForwardTarget([], '!first'), ['!first']);
});
