import { describe, test, expect } from 'vitest';
import { relayFormWiring } from './form-relay-wiring';

describe('relayFormWiring deterministic + unique fid (thread node id, no Math.random)', () => {
  test('no recipient: no relay, no marker, no fid needed', () => {
    const wiring = relayFormWiring(undefined, undefined, '/legacy', 'node-1');
    expect(wiring.useRelay).toBe(false);
    expect(wiring.marker).toBe('');
  });

  test('same node id -> identical marker + placeholder ids across two calls (deterministic)', () => {
    const w1 = relayFormWiring('a@b.com', '/thx', undefined, 'node-form1');
    const w2 = relayFormWiring('a@b.com', '/thx', undefined, 'node-form1');
    expect(w1.marker).toBe(w2.marker);
    expect(w1.actionAttr).toBe(w2.actionAttr);
  });

  test('marker id and placeholder id always match each other', () => {
    const w = relayFormWiring('a@b.com', '/thx', undefined, 'node-form1');
    const mid = w.marker.match(/id="([^"]+)"/)![1];
    expect(w.actionAttr).toBe(`__WHP_FORM_ACTION__${mid}__`);
  });

  test('different node ids -> different fids (no collision)', () => {
    const w1 = relayFormWiring('a@b.com', '/thx', undefined, 'node-form1');
    const w2 = relayFormWiring('a@b.com', '/thx', undefined, 'node-form2');
    const mid1 = w1.marker.match(/id="([^"]+)"/)![1];
    const mid2 = w2.marker.match(/id="([^"]+)"/)![1];
    expect(mid1).not.toBe(mid2);
  });

  test('no nodeId (legacy call): still deterministic across repeated calls, not random', () => {
    const w1 = relayFormWiring('a@b.com', '/thx', undefined);
    const w2 = relayFormWiring('a@b.com', '/thx', undefined);
    expect(w1.marker).toBe(w2.marker);
    expect(w1.actionAttr).toBe(w2.actionAttr);
  });
});
