import assert from 'node:assert/strict';
import test from 'node:test';
import { isMissingReceiverError, withContentReceiverReady } from '../src/content-channel.js';

test('recognizes Firefox and Chromium missing content-script receiver errors', () => {
  assert.equal(isMissingReceiverError(new Error('Could not establish connection. Receiving end does not exist.')), true);
  assert.equal(isMissingReceiverError(new Error('Receiving end does not exist.')), true);
  assert.equal(isMissingReceiverError(new Error('HOST_UI_CHANGED')), false);
});

test('retries only missing receiver failures until content script is ready', async () => {
  let attempts = 0;
  const waits: number[] = [];
  const result = await withContentReceiverReady(async () => {
    attempts += 1;
    if (attempts < 3) throw new Error('Could not establish connection. Receiving end does not exist.');
    return 'ready';
  }, 5_000, async (ms) => { waits.push(ms); });
  assert.equal(result, 'ready');
  assert.equal(attempts, 3);
  assert.deepEqual(waits, [50, 100]);
});

test('does not retry non-transient content errors', async () => {
  let attempts = 0;
  await assert.rejects(() => withContentReceiverReady(async () => {
    attempts += 1;
    throw new Error('HOST_UI_CHANGED: composer missing');
  }, 5_000, async () => {}), /HOST_UI_CHANGED/);
  assert.equal(attempts, 1);
});
