import { describe, test, expect } from 'bun:test';
import { formatRecoveryCard } from '../src/components/recovery/RecoverySetup.js';
import { createApprovalQueue } from '../src/components/recovery/RecoveryApprove.js';

describe('formatRecoveryCard', () => {
  test('renders all fields the user must keep', () => {
    const text = formatRecoveryCard(
      'alice@example',
      {
        setupId: 'sid-123',
        threshold: 3,
        guardianCount: 5,
        deliveries: [],
        allDelivered: true,
        setupFingerprint: '11111 22222 33333 44444 55555 66666 77777 88888 99999 00000 11111 22222',
      },
      ['bob@example', 'carol@example', 'dan@example', 'eve@example', 'faythe@example'],
    );
    expect(text).toContain('alice@example');
    expect(text).toContain('Threshold: 3 of 5');
    expect(text).toContain('SetupId: sid-123');
    expect(text).toContain('Setup fingerprint:');
    expect(text).toContain('bob@example');
    expect(text).toContain('faythe@example');
  });
});

describe('createApprovalQueue', () => {
  test('queues approve calls and resolves on user decision', async () => {
    const q = createApprovalQueue();
    const approvePromise = q.approve({
      requesterAddress: 'alice2',
      originalAddress: 'alice',
      setupId: 'sid-1',
      requesterFingerprint: 'aaa',
      setupFingerprint: 'bbb',
      depositCreatedAt: 0,
      requestReceivedAt: 1,
    });
    const pending = q.pending();
    expect(pending.length).toBe(1);
    q.resolve(pending[0]!.id, true);
    const decision = await approvePromise;
    expect(decision).toBe(true);
    expect(q.pending().length).toBe(0);
  });

  test('decline path resolves false', async () => {
    const q = createApprovalQueue();
    const p = q.approve({
      requesterAddress: 'eve',
      originalAddress: 'alice',
      setupId: 'sid-1',
      requesterFingerprint: 'aaa',
      setupFingerprint: 'bbb',
      depositCreatedAt: 0,
      requestReceivedAt: 1,
    });
    q.resolve(q.pending()[0]!.id, false);
    expect(await p).toBe(false);
  });

  test('subscribe fires on new pending + resolve', async () => {
    const q = createApprovalQueue();
    const events: string[] = [];
    const unsub = q.subscribe(() => events.push('change'));
    q.approve({
      requesterAddress: 'a',
      originalAddress: 'b',
      setupId: 's',
      requesterFingerprint: 'x',
      setupFingerprint: 'y',
      depositCreatedAt: 0,
      requestReceivedAt: 1,
    }).catch(() => {});
    expect(events.length).toBe(1);
    q.resolve(q.pending()[0]!.id, false);
    expect(events.length).toBe(2);
    unsub();
  });
});
