import { describe, expect, it, vi } from 'vitest';
import { DeferredResourceLifecycle } from '../../src/ffmpeg/engine-lifecycle';

describe('singleton engine lifecycle', () => {
  it('cancels deferred disposal when StrictMode immediately reacquires', () => {
    const dispose = vi.fn();
    const deferred: Array<() => void> = [];
    const lifecycle = new DeferredResourceLifecycle({ dispose }, (callback) =>
      deferred.push(callback)
    );

    const releaseFirstMount = lifecycle.acquire();
    releaseFirstMount();
    const releaseStrictModeRemount = lifecycle.acquire();
    deferred.shift()?.();

    expect(dispose).not.toHaveBeenCalled();
    expect(lifecycle.leaseCount).toBe(1);

    releaseStrictModeRemount();
    deferred.shift()?.();
    expect(dispose).toHaveBeenCalledOnce();
    expect(lifecycle.leaseCount).toBe(0);
  });

  it('disposes only after the last lease and ignores duplicate releases', () => {
    const dispose = vi.fn();
    const deferred: Array<() => void> = [];
    const lifecycle = new DeferredResourceLifecycle({ dispose }, (callback) =>
      deferred.push(callback)
    );
    const releaseOne = lifecycle.acquire();
    const releaseTwo = lifecycle.acquire();

    releaseOne();
    releaseOne();
    expect(deferred).toHaveLength(0);
    expect(lifecycle.leaseCount).toBe(1);

    releaseTwo();
    expect(deferred).toHaveLength(1);
    deferred[0]?.();
    expect(dispose).toHaveBeenCalledOnce();
  });
});
