import { afterEach, describe, expect, it } from 'vitest';
import { confirm, useConfirmStore } from './ConfirmStore';

afterEach(() => {
  // Resolve any dangling request so promises never leak between tests.
  useConfirmStore.getState().resolve(false);
  useConfirmStore.setState({ request: null });
});

describe('ConfirmStore', () => {
  it('opens a request carrying the provided options', () => {
    void confirm({ title: 'Delete snippet', message: 'Cannot be undone.', danger: true });
    const req = useConfirmStore.getState().request;
    expect(req).not.toBeNull();
    expect(req?.title).toBe('Delete snippet');
    expect(req?.message).toBe('Cannot be undone.');
    expect(req?.danger).toBe(true);
  });

  it('resolves true when accepted and clears the request', async () => {
    const p = confirm({ title: 'T', message: 'M' });
    useConfirmStore.getState().resolve(true);
    await expect(p).resolves.toBe(true);
    expect(useConfirmStore.getState().request).toBeNull();
  });

  it('resolves false when cancelled and clears the request', async () => {
    const p = confirm({ title: 'T', message: 'M' });
    useConfirmStore.getState().resolve(false);
    await expect(p).resolves.toBe(false);
    expect(useConfirmStore.getState().request).toBeNull();
  });

  it('resolve() with no open request is a no-op', () => {
    expect(() => useConfirmStore.getState().resolve(true)).not.toThrow();
    expect(useConfirmStore.getState().request).toBeNull();
  });

  it('opening a second confirmation cancels the first (no hung awaiter)', async () => {
    const first = confirm({ title: 'First', message: 'M' });
    const second = confirm({ title: 'Second', message: 'M' });

    // The first awaiter settles false immediately; the second is now open.
    await expect(first).resolves.toBe(false);
    expect(useConfirmStore.getState().request?.title).toBe('Second');

    useConfirmStore.getState().resolve(true);
    await expect(second).resolves.toBe(true);
  });
});
