import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createStore } from 'jotai';
import { getThreadDraftKey, roomIdToActiveThreadIdAtomFamily } from './thread';

// ---------------------------------------------------------------------------
// getThreadDraftKey
// ---------------------------------------------------------------------------

test('getThreadDraftKey joins roomId and threadRootId with "::"', () => {
  assert.equal(getThreadDraftKey('!room:server', '$root'), '!room:server::$root');
});

test('getThreadDraftKey keeps the two ids distinguishable', () => {
  assert.notEqual(getThreadDraftKey('!a:server', '$b'), getThreadDraftKey('!a:server', '$c'));
});

// ---------------------------------------------------------------------------
// roomIdToActiveThreadIdAtomFamily
// ---------------------------------------------------------------------------

test('returns the same atom instance for the same roomId', () => {
  const a = roomIdToActiveThreadIdAtomFamily('!room:server');
  const b = roomIdToActiveThreadIdAtomFamily('!room:server');
  assert.equal(a, b);
});

test('returns different atoms for different roomIds', () => {
  const a = roomIdToActiveThreadIdAtomFamily('!a:server');
  const b = roomIdToActiveThreadIdAtomFamily('!b:server');
  assert.notEqual(a, b);
});

test('the active-thread atom defaults to null and is writable', () => {
  const store = createStore();
  const activeThreadIdAtom = roomIdToActiveThreadIdAtomFamily('!store:server');

  assert.equal(store.get(activeThreadIdAtom), null);
  store.set(activeThreadIdAtom, '$root');
  assert.equal(store.get(activeThreadIdAtom), '$root');
  store.set(activeThreadIdAtom, null);
  assert.equal(store.get(activeThreadIdAtom), null);
});
