import { describe, expect, it } from 'vitest';

import { SourceInspectionRegistry } from '../../src/app/source-inspection-registry';

describe('SourceInspectionRegistry', () => {
  it('invalidates queued work synchronously and does not request cancellation', () => {
    const registry = new SourceInspectionRegistry();
    const token = registry.register('queued');

    expect(registry.remove('queued')).toBe(false);
    expect(registry.isCurrent(token)).toBe(false);
    expect(registry.activate(token)).toBe(false);
    expect(token.signal.aborted).toBe(true);
  });

  it('requests cancellation for the active asset and rejects its late result', () => {
    const registry = new SourceInspectionRegistry();
    const token = registry.register('active');

    expect(registry.activate(token)).toBe(true);
    expect(registry.remove('active')).toBe(true);
    expect(registry.isCurrent(token)).toBe(false);
    expect(token.signal.aborted).toBe(true);
    registry.finish(token);
    expect(registry.remove('active')).toBe(false);
  });

  it('does not let a late generation overwrite a replacement with the same ID', () => {
    const registry = new SourceInspectionRegistry();
    const stale = registry.register('reattached');
    expect(registry.activate(stale)).toBe(true);

    const replacement = registry.register('reattached');
    expect(registry.isCurrent(stale)).toBe(false);
    expect(registry.isCurrent(replacement)).toBe(true);
    expect(stale.signal.aborted).toBe(true);
    expect(replacement.signal.aborted).toBe(false);
    registry.finish(stale);
    expect(registry.activate(replacement)).toBe(true);
  });

  it('invalidates all queued work and identifies an active probe on clear', () => {
    const registry = new SourceInspectionRegistry();
    const active = registry.register('active');
    const queued = registry.register('queued');
    registry.activate(active);

    expect(registry.clear()).toBe(true);
    expect(registry.isCurrent(active)).toBe(false);
    expect(registry.isCurrent(queued)).toBe(false);
  });
});
