import { plainToInstance } from 'class-transformer';
import { validateSync } from 'class-validator';
import { AnularGastoDto } from './dto/anular-gasto.dto';
import { MotivoAnulacionRendicionDto } from 'src/rendicion-viaticos/dto/motivo-anulacion.dto';
import {
  MAX_MOTIVO_ANULACION_GASTO,
  MAX_MOTIVO_ANULACION_RENDICION,
  motivoLimpio,
  motivoVacio,
  motivoGastoDeRendicionAnulada,
  motivoGastoQuitadoDeRendicion,
} from './motivo-anulacion';

/**
 * C2: el motivo termina en tes_movimientos.motivo_anulacion y tes_cheques.motivo
 * (VarChar 500). Uno más largo hacía fallar la reversión de Tesorería.
 */
const errores = (cls: any, motivo: string) => validateSync(plainToInstance(cls, { motivo }) as object);

describe('Largo del motivo de anulación', () => {
  it('gasto: 500 entra, 501 da error de validación', () => {
    expect(errores(AnularGastoDto, 'a'.repeat(MAX_MOTIVO_ANULACION_GASTO))).toHaveLength(0);
    expect(errores(AnularGastoDto, 'a'.repeat(MAX_MOTIVO_ANULACION_GASTO + 1))).not.toHaveLength(0);
  });

  it('rendición: el máximo deja lugar al prefijo con el número de rendición más largo (30)', () => {
    expect(MAX_MOTIVO_ANULACION_RENDICION).toBe(444);
    const numero = 'R'.repeat(30);
    const motivo = 'a'.repeat(MAX_MOTIVO_ANULACION_RENDICION);
    expect(motivoGastoDeRendicionAnulada(numero, motivo).length).toBeLessThanOrEqual(500);
    expect(motivoGastoQuitadoDeRendicion(numero, motivo).length).toBeLessThanOrEqual(500);
    expect(errores(MotivoAnulacionRendicionDto, motivo)).toHaveLength(0);
    expect(errores(MotivoAnulacionRendicionDto, motivo + 'a')).not.toHaveLength(0);
  });
});

describe('motivoLimpio y motivoVacio', () => {
  it('recorta los bordes y devuelve el texto', () => {
    expect(motivoLimpio('  Error de carga  ', 20)).toBe('Error de carga');
  });
  it('null si queda vacío (también con null, undefined o solo espacios)', () => {
    for (const v of ['', '   ', null, undefined]) {
      expect(motivoLimpio(v, 20)).toBeNull();
      expect(motivoVacio(v)).toBe(true);
    }
  });
  it('null si supera el máximo, y ahí motivoVacio es false; el máximo exacto pasa', () => {
    expect(motivoLimpio('x'.repeat(21), 20)).toBeNull();
    expect(motivoVacio('x'.repeat(21))).toBe(false);
    expect(motivoLimpio(` ${'x'.repeat(20)} `, 20)).toBe('x'.repeat(20));
  });
});
