import { RequisicionAprobacionConfigItemDto } from './dto/requisicion-config.dto';
import { validarNiveles } from './reglas-niveles';

const P1 = '11111111-1111-4111-8111-111111111111';
const P2 = '22222222-2222-4222-8222-222222222222';
const PERFILES = new Map([
  [P1, { puede_aprobar: true }],
  [P2, { puede_aprobar: false }],
]);
const item = (o: Partial<RequisicionAprobacionConfigItemDto> = {}): RequisicionAprobacionConfigItemDto => ({
  origen_tipo: 'compra',
  nivel: 1,
  perfil_id: P1,
  monto_desde: 0,
  monto_hasta: null,
  ...o,
});
const rechazo = (items: RequisicionAprobacionConfigItemDto[], perfiles = PERFILES) => {
  try {
    validarNiveles(items, perfiles);
  } catch (e: any) {
    return { status: e.getStatus(), ...e.getResponse() };
  }
  throw new Error('no lanzó');
};

describe('validarNiveles', () => {
  it('hasta < desde: NIVEL_RANGO_INVALIDO con linea y origen (la línea cuenta dentro del origen)', () => {
    const r = rechazo([item({ origen_tipo: 'compra' }), item({ origen_tipo: 'gasto', nivel: 1 }), item({ origen_tipo: 'gasto', nivel: 2, monto_desde: 500, monto_hasta: 100 })]);
    expect(r).toMatchObject({ status: 400, codigo: 'NIVEL_RANGO_INVALIDO', linea: 2, origen: 'gasto', campo: 'monto_hasta' });
  });

  it('dos niveles 1 en compra: 409 NIVEL_REPETIDO en la segunda línea', () => {
    expect(rechazo([item(), item({ monto_desde: 10 })])).toMatchObject({ status: 409, codigo: 'NIVEL_REPETIDO', linea: 2, origen: 'compra' });
  });

  it('el mismo nivel en compra y en gasto pasa', () => {
    expect(() => validarNiveles([item(), item({ origen_tipo: 'gasto' })], PERFILES)).not.toThrow();
  });

  it('perfil que no es de la empresa: PERFIL_NO_ENCONTRADO', () => {
    expect(rechazo([item({ perfil_id: '99999999-9999-4999-8999-999999999999' })])).toMatchObject({ status: 400, codigo: 'PERFIL_NO_ENCONTRADO', linea: 1 });
  });

  it('perfil sin _APROBAR: PERFIL_SIN_PERMISO_APROBAR con linea y origen', () => {
    expect(rechazo([item(), item({ nivel: 2, perfil_id: P2, monto_desde: 5 })])).toMatchObject({
      status: 400,
      codigo: 'PERFIL_SIN_PERMISO_APROBAR',
      linea: 2,
      origen: 'compra',
    });
  });

  it('huecos y superpuestos pasan (D2: los niveles se acumulan y el hueco solo se avisa en pantalla)', () => {
    expect(() =>
      validarNiveles([item({ monto_hasta: 100 }), item({ nivel: 2, monto_desde: 5_000, monto_hasta: null }), item({ nivel: 3, monto_desde: 50 })], PERFILES),
    ).not.toThrow();
  });

  it('sin niveles pasa (el vaciado lo controla NIVELES_VACIOS en el servicio)', () => {
    expect(() => validarNiveles([], PERFILES)).not.toThrow();
  });
});
