import { BadRequestException } from '@nestjs/common';
import { leerImagenes, MAX_BYTES_IMAGEN } from './imagenes';

const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0]);
const JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 0]);
const WEBP = Buffer.concat([Buffer.from('RIFF'), Buffer.alloc(4), Buffer.from('WEBPVP8 ')]);
const b64 = (b: Buffer) => b.toString('base64');

describe('capturas del cliente', () => {
  it('acepta PNG, JPEG y WebP de verdad', () => {
    const r = leerImagenes([
      { tipo: 'image/png', datos: b64(PNG) },
      { tipo: 'image/jpeg', datos: b64(JPEG) },
      { tipo: 'image/webp', datos: b64(WEBP) },
    ]);
    expect(r.map((x) => x.tipo)).toEqual(['image/png', 'image/jpeg', 'image/webp']);
    expect(r[0].datos.equals(PNG)).toBe(true);
  });

  it('sin capturas, nada', () => {
    expect(leerImagenes()).toEqual([]);
  });

  it.each([
    ['un tipo que no es imagen', [{ tipo: 'image/svg+xml', datos: b64(PNG) }]],
    ['un tipo que no coincide con los bytes', [{ tipo: 'image/png', datos: b64(JPEG) }]],
    ['un HTML disfrazado de PNG', [{ tipo: 'image/png', datos: b64(Buffer.from('<html><script>')) }]],
    ['vacía', [{ tipo: 'image/png', datos: '' }]],
    ['más de 3', Array.from({ length: 4 }, () => ({ tipo: 'image/png', datos: b64(PNG) }))],
    ['demasiado pesada', [{ tipo: 'image/png', datos: b64(Buffer.concat([PNG, Buffer.alloc(MAX_BYTES_IMAGEN)])) }]],
  ])('rechaza %s', (_, entrada) => {
    expect(() => leerImagenes(entrada)).toThrow(BadRequestException);
  });
});
