import { acreditable, resolverMonedaNc, terminoNumeroNc } from './reglas-nc-compra';

/** Reglas puras de la NC de compra (plan 2026-10-22-nc-compra, Task 3). */

const PYG = 'pyg';
const USD = 'usd';
const base = { monedaBaseId: PYG, pygId: PYG };

/** Ejecuta y devuelve el cuerpo del error estructurado (o falla si no lanza). */
function errorDe(fn: () => unknown): { codigo: string; campo?: string } {
  try {
    fn();
  } catch (e: any) {
    return e.getResponse();
  }
  throw new Error('No lanzó');
}

describe('resolverMonedaNc', () => {
  it('con origen PYG devuelve la moneda y cotización 1', () => {
    expect(resolverMonedaNc({ ...base, origen: { moneda_id: PYG, cotizacion: 1 } })).toEqual({
      moneda_id: PYG,
      cotizacion: 1,
    });
  });

  it('con origen USD 7300 devuelve 7300 aunque el dto mande 7000', () => {
    expect(
      resolverMonedaNc({
        ...base,
        origen: { moneda_id: USD, cotizacion: 7300 },
        dtoMonedaId: USD,
        dtoCotizacion: 7000,
      }),
    ).toEqual({
      moneda_id: USD,
      cotizacion: 7300,
    });
  });

  it('con origen USD y dto moneda PYG lanza MONEDA_DISTINTA_ORIGEN', () => {
    expect(
      errorDe(() => resolverMonedaNc({ ...base, origen: { moneda_id: USD, cotizacion: 7300 }, dtoMonedaId: PYG })),
    ).toMatchObject({
      codigo: 'MONEDA_DISTINTA_ORIGEN',
      campo: 'moneda_id',
    });
  });

  it('origen USD con cotización 1 y sin dto lanza COTIZACION_REQUERIDA; con dto 7300 la usa', () => {
    expect(errorDe(() => resolverMonedaNc({ ...base, origen: { moneda_id: USD, cotizacion: 1 } }))).toMatchObject({
      codigo: 'COTIZACION_REQUERIDA',
      campo: 'cotizacion',
    });
    expect(resolverMonedaNc({ ...base, origen: { moneda_id: USD, cotizacion: 1 }, dtoCotizacion: 7300 })).toEqual({
      moneda_id: USD,
      cotizacion: 7300,
    });
  });

  it('origen sin moneda → PYG', () => {
    expect(resolverMonedaNc({ ...base, origen: { moneda_id: null, cotizacion: 1 } })).toEqual({
      moneda_id: PYG,
      cotizacion: 1,
    });
    // Aunque la empresa tenga otra moneda base, el origen sin moneda se toma en PYG.
    expect(
      resolverMonedaNc({
        monedaBaseId: USD,
        pygId: PYG,
        origen: { moneda_id: null, cotizacion: 1 },
        dtoCotizacion: 0.000137,
      }),
    ).toEqual({ moneda_id: PYG, cotizacion: 0.000137 });
  });

  it('sin origen y sin moneda lanza MONEDA_REQUERIDA', () => {
    expect(errorDe(() => resolverMonedaNc({ ...base, origen: null }))).toMatchObject({
      codigo: 'MONEDA_REQUERIDA',
      campo: 'moneda_id',
    });
  });

  it('sin origen USD con cotización 1 lanza COTIZACION_INVALIDA; con 0 también; con 7300 la acepta', () => {
    expect(
      errorDe(() => resolverMonedaNc({ ...base, origen: null, dtoMonedaId: USD, dtoCotizacion: 1 })),
    ).toMatchObject({
      codigo: 'COTIZACION_INVALIDA',
      campo: 'cotizacion',
    });
    expect(
      errorDe(() => resolverMonedaNc({ ...base, origen: null, dtoMonedaId: USD, dtoCotizacion: 0 })),
    ).toMatchObject({
      codigo: 'COTIZACION_INVALIDA',
      campo: 'cotizacion',
    });
    expect(errorDe(() => resolverMonedaNc({ ...base, origen: null, dtoMonedaId: USD }))).toMatchObject({
      codigo: 'COTIZACION_REQUERIDA',
      campo: 'cotizacion',
    });
    expect(resolverMonedaNc({ ...base, origen: null, dtoMonedaId: USD, dtoCotizacion: 7300 })).toEqual({
      moneda_id: USD,
      cotizacion: 7300,
    });
  });

  it('sin origen en moneda base devuelve 1', () => {
    expect(resolverMonedaNc({ ...base, origen: null, dtoMonedaId: PYG, dtoCotizacion: 7300 })).toEqual({
      moneda_id: PYG,
      cotizacion: 1,
    });
  });
  it('origen con cotización menor a 1 legítima (base USD, origen PYG 0.000137) se conserva', () => {
    expect(
      resolverMonedaNc({
        monedaBaseId: USD,
        pygId: PYG,
        origen: { moneda_id: PYG, cotizacion: 0.000137 },
        dtoCotizacion: 0.0002,
      }),
    ).toEqual({ moneda_id: PYG, cotizacion: 0.000137 });
  });

  it('origen con cotización 1 (o ≤ 0) en moneda que no es la base y sin valor del cliente → COTIZACION_REQUERIDA', () => {
    expect(
      errorDe(() => resolverMonedaNc({ monedaBaseId: USD, pygId: PYG, origen: { moneda_id: PYG, cotizacion: 1 } })),
    ).toMatchObject({
      codigo: 'COTIZACION_REQUERIDA',
      campo: 'cotizacion',
    });
    expect(errorDe(() => resolverMonedaNc({ ...base, origen: { moneda_id: USD, cotizacion: 0 } }))).toMatchObject({
      codigo: 'COTIZACION_REQUERIDA',
      campo: 'cotizacion',
    });
  });
});

describe('acreditable', () => {
  it('acreditable(1000, [300, 200]) === 500; nunca negativo', () => {
    expect(acreditable(1000, [300, 200])).toBe(500);
    expect(acreditable(1000, [])).toBe(1000);
    expect(acreditable(1000, [800, 400])).toBe(0);
  });
});

describe('terminoNumeroNc', () => {
  it("terminoNumeroNc('001-002-45') → { establecimiento '001', punto_expedicion '002', numero '0000045' }; 'abc' → null", () => {
    expect(terminoNumeroNc('001-002-45')).toEqual({
      establecimiento: '001',
      punto_expedicion: '002',
      numero: '0000045',
    });
    expect(terminoNumeroNc(' 1-2 ')).toEqual({ establecimiento: '001', punto_expedicion: '002' });
    expect(terminoNumeroNc('abc')).toBeNull();
    expect(terminoNumeroNc('')).toBeNull();
  });
});
