import { bloquearNumeroRequisicion, bloquearRequisiciones } from './bloqueos-oc';

/** Las claves de lock en el orden en que se tomaron. */
const claves = (tx: { $executeRaw: jest.Mock }) => tx.$executeRaw.mock.calls.map((c: unknown[]) => c[1]);

describe('bloqueos-oc', () => {
  it('bloquearNumeroRequisicion toma req-num:<empresa>', async () => {
    const tx = { $executeRaw: jest.fn().mockResolvedValue(1) };
    await bloquearNumeroRequisicion(tx as never, 'emp-1');
    expect(tx.$executeRaw).toHaveBeenCalledTimes(1);
    const [strings, ...valores] = tx.$executeRaw.mock.calls[0];
    expect(strings.join('?')).toContain('pg_advisory_xact_lock(hashtext(');
    expect(valores).toEqual(['req-num:emp-1']);
  });

  it('bloquearRequisiciones: ordenadas, sin repetir y sin vacíos', async () => {
    const tx = { $executeRaw: jest.fn().mockResolvedValue(1) };
    await bloquearRequisiciones(tx as never, ['req-b', null, 'req-a', undefined, 'req-b']);
    expect(claves(tx)).toEqual(['req:req-a', 'req:req-b']);
  });

  it('dos ediciones cruzadas (de A a B y de B a A) toman los locks en el mismo orden', async () => {
    const deAaB = { $executeRaw: jest.fn().mockResolvedValue(1) };
    const deBaA = { $executeRaw: jest.fn().mockResolvedValue(1) };
    // Cada edición pasa [requisición guardada, requisición nueva].
    await bloquearRequisiciones(deAaB as never, ['req-a', 'req-b']);
    await bloquearRequisiciones(deBaA as never, ['req-b', 'req-a']);
    expect(claves(deAaB)).toEqual(['req:req-a', 'req:req-b']);
    expect(claves(deBaA)).toEqual(claves(deAaB));
  });
});
