import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createStore } from 'jotai';
import { allInvitesAtom } from './inviteList';

// allInvitesAtom shares the roomList reducer shape over an unexported string[]
// baseRoomsAtom: INITIALIZE replace, PUT move-to-end dedupe, DELETE filter-out.
// The React binding hook (useBindAllInvitesAtom) is not covered.

const R1 = '!r1:server';
const R2 = '!r2:server';
const R3 = '!r3:server';

test('starts empty', () => {
  const store = createStore();
  assert.deepEqual(store.get(allInvitesAtom), []);
});

test('INITIALIZE replaces the whole list', () => {
  const store = createStore();
  store.set(allInvitesAtom, { type: 'PUT', roomId: R1 });
  store.set(allInvitesAtom, { type: 'INITIALIZE', rooms: [R2, R3] });
  assert.deepEqual(store.get(allInvitesAtom), [R2, R3]);
});

test('PUT appends a new invite', () => {
  const store = createStore();
  store.set(allInvitesAtom, { type: 'PUT', roomId: R1 });
  store.set(allInvitesAtom, { type: 'PUT', roomId: R2 });
  assert.deepEqual(store.get(allInvitesAtom), [R1, R2]);
});

test('PUT of an existing invite moves it to the end (dedupe)', () => {
  const store = createStore();
  store.set(allInvitesAtom, { type: 'INITIALIZE', rooms: [R1, R2, R3] });
  store.set(allInvitesAtom, { type: 'PUT', roomId: R1 });
  assert.deepEqual(store.get(allInvitesAtom), [R2, R3, R1]);
});

test('DELETE removes an invite', () => {
  const store = createStore();
  store.set(allInvitesAtom, { type: 'INITIALIZE', rooms: [R1, R2, R3] });
  store.set(allInvitesAtom, { type: 'DELETE', roomId: R2 });
  assert.deepEqual(store.get(allInvitesAtom), [R1, R3]);
});

test('DELETE of an absent invite is a no-op', () => {
  const store = createStore();
  store.set(allInvitesAtom, { type: 'INITIALIZE', rooms: [R1] });
  store.set(allInvitesAtom, { type: 'DELETE', roomId: R2 });
  assert.deepEqual(store.get(allInvitesAtom), [R1]);
});
