import { test } from 'node:test';
import assert from 'node:assert/strict';
// Importing the module evaluates `atomWithStorage(..., createJSONStorage(() => localStorage))`,
// which touches `localStorage` at load time. node has none, so install a no-op
// mock before the import is resolved.
(globalThis as { localStorage?: unknown }).localStorage = {
  getItem: () => null,
  setItem: () => undefined,
  removeItem: () => undefined,
};

// eslint-disable-next-line import/first
import { addRecentSearch } from './recentSearches';

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

test('addRecentSearch dedupes (case-sensitive) and moves the term to the front', () => {
  assert.deepEqual(addRecentSearch(['a', 'b', 'c'], 'b'), ['b', 'a', 'c']);
  // case-sensitive: differing case is treated as a distinct term
  assert.deepEqual(addRecentSearch(['a', 'B'], 'b'), ['b', 'a', 'B']);
});

test('addRecentSearch trims whitespace before storing', () => {
  assert.deepEqual(addRecentSearch(['a'], '  hello  '), ['hello', 'a']);
  // dedupe compares against the trimmed value
  assert.deepEqual(addRecentSearch(['hello'], '  hello '), ['hello']);
});

test('addRecentSearch ignores empty / whitespace-only terms', () => {
  assert.deepEqual(addRecentSearch(['a', 'b'], ''), ['a', 'b']);
  assert.deepEqual(addRecentSearch(['a', 'b'], '   '), ['a', 'b']);
});

test('addRecentSearch caps the list at 10 entries', () => {
  const ten = Array.from({ length: 10 }, (_, i) => `t${i}`);
  const result = addRecentSearch(ten, 'new');
  assert.equal(result.length, 10);
  assert.equal(result[0], 'new');
  // the oldest entry (last) is dropped
  assert.equal(result.includes('t9'), false);
  assert.deepEqual(result.slice(1), ten.slice(0, 9));
});

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