import test from 'node:test';
import assert from 'node:assert/strict';
import { selectNotificationMessageIdsToDelete } from './notification-message-prune.js';
import { pruneNotificationMessageTargetClientIds } from './notification-message-service.js';

test('selectNotificationMessageIdsToDelete keeps only the latest notification by createdAt and id', () => {
  const ids = selectNotificationMessageIdsToDelete([
    { id: 1, createdAt: '2026-05-06T03:00:00.000Z' },
    { id: 2, createdAt: '2026-05-06T05:00:00.000Z' },
    { id: 3, createdAt: '2026-05-06T05:00:00.000Z' },
    { id: 4, createdAt: '2026-05-06T01:00:00.000Z' },
  ]);

  assert.deepEqual(ids, [2, 1, 4]);
});

test('selectNotificationMessageIdsToDelete respects keepLatestCount', () => {
  const ids = selectNotificationMessageIdsToDelete([
    { id: 10, createdAt: '2026-05-06T02:00:00.000Z' },
    { id: 11, createdAt: '2026-05-06T03:00:00.000Z' },
    { id: 12, createdAt: '2026-05-06T04:00:00.000Z' },
  ], 2);

  assert.deepEqual(ids, [10]);
});

test('pruneNotificationMessageTargetClientIds removes stale clients and preserves active targets', () => {
  const result = pruneNotificationMessageTargetClientIds(
    {
      sessionId: 'chat-room',
      targetClientIds: ['client-active', 'client-stale-1', 'client-stale-2'],
    },
    ['client-stale-1', 'client-stale-2'],
  );

  assert.deepEqual(result.targetClientIds, ['client-active']);
  assert.equal(result.hasTargets, true);
  assert.equal(result.changed, true);
  assert.deepEqual(result.metadata.targetClientIds, ['client-active']);
});

test('pruneNotificationMessageTargetClientIds marks rows empty when every target becomes stale', () => {
  const result = pruneNotificationMessageTargetClientIds(
    {
      sessionId: 'chat-room',
      targetClientIds: ['client-stale-1'],
    },
    ['client-stale-1'],
  );

  assert.deepEqual(result.targetClientIds, []);
  assert.equal(result.hasTargets, false);
  assert.equal(result.changed, true);
  assert.deepEqual(result.metadata.targetClientIds, []);
});
