import { BadRequestException } from '@nestjs/common';
import sharp from 'sharp';
import { envs } from 'src/config/envs';
import { estaVacia, FirmaImagenService, normalizarImagenFirma } from './firma-imagen.service';
import { FirmaReciboService } from './firma-recibo.service';

const EMP = '11111111-1111-1111-1111-111111111111';

/** Hoja blanca de 1600×1000 con un trazo negro en el medio: lo que sale de escanear una firma. */
const hojaConFirma = () =>
  sharp({ create: { width: 1600, height: 1000, channels: 3, background: '#ffffff' } })
    .composite([{ input: { create: { width: 600, height: 200, channels: 3, background: '#000000' } }, left: 500, top: 400 }])
    .jpeg()
    .toBuffer();

describe('imagen de firma y sello de los recibos', () => {
  it('se achica, se recorta el papel alrededor y sale PNG', async () => {
    const salida = await normalizarImagenFirma(await hojaConFirma());
    const m = await sharp(salida).metadata();
    expect(m.format).toBe('png');
    // Recortado al trazo (600×200, proporción 3:1) y dentro de 800×400.
    expect(m.width).toBeLessThanOrEqual(800);
    expect(m.height).toBeLessThanOrEqual(400);
    expect(Math.round(m.width! / m.height!)).toBe(3);
  });

  it('una foto con el papel gris: el papel queda transparente y la tinta opaca, con su color', async () => {
    const foto = await sharp({ create: { width: 800, height: 500, channels: 3, background: '#c9c6bd' } })
      .composite([{ input: { create: { width: 300, height: 80, channels: 3, background: '#1d2a6b' } }, left: 250, top: 200 }])
      .jpeg()
      .toBuffer();
    const { data, info } = await sharp(await normalizarImagenFirma(foto)).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
    const px = (x: number, y: number) => Array.from(data.subarray((y * info.width + x) * 4, (y * info.width + x) * 4 + 4));
    // Recortado a la tinta: el centro es tinta azul opaca.
    const centro = px(Math.floor(info.width / 2), Math.floor(info.height / 2));
    expect(centro[3]).toBe(255);
    expect(centro[2]).toBeGreaterThan(centro[0]);
    expect(info.width).toBeLessThanOrEqual(310);
  });

  it('el papel alrededor de la tinta (sin recortar) es transparente', async () => {
    // Dos trazos separados: entre ellos queda papel adentro del recorte.
    const foto = await sharp({ create: { width: 800, height: 400, channels: 3, background: '#e8e4da' } })
      .composite([
        { input: { create: { width: 60, height: 60, channels: 3, background: '#111111' } }, left: 100, top: 150 },
        { input: { create: { width: 60, height: 60, channels: 3, background: '#111111' } }, left: 600, top: 150 },
      ])
      .png()
      .toBuffer();
    const { data, info } = await sharp(await normalizarImagenFirma(foto)).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
    const medio = (Math.floor(info.height / 2) * info.width + Math.floor(info.width / 2)) * 4;
    expect(data[medio + 3]).toBe(0);
  });

  it('una hoja en blanco no se guarda: avisa que no se ve ninguna firma', async () => {
    const lisa = await sharp({ create: { width: 300, height: 100, channels: 3, background: '#ffffff' } }).png().toBuffer();
    await expect(normalizarImagenFirma(lisa)).rejects.toThrow(/no se ve ninguna firma/);
  });

  // Caso real (DOBA, 18/11): un PNG ya recortado, con el fondo transparente. Lo visible es solo la tinta y se la tomaba
  // por el papel: la firma quedaba toda transparente y el recibo salía con el recuadro vacío.
  it('un PNG que ya viene con el fondo transparente se respeta: la firma no desaparece', async () => {
    const tinta = { r: 76, g: 105, b: 113 };
    const ancho = 400;
    const alto = 300;
    const px = Buffer.alloc(ancho * alto * 4);
    for (let y = 0; y < alto; y++)
      for (let x = 0; x < ancho; x++) {
        const o = (y * ancho + x) * 4;
        // Los píxeles transparentes traen el mismo color que la tinta (como lo dejan los recortadores de fondo).
        px[o] = tinta.r;
        px[o + 1] = tinta.g;
        px[o + 2] = tinta.b;
        px[o + 3] = Math.abs(y - (alto / 2 + 60 * Math.sin(x / 30))) < 6 ? 255 : 0;
      }
    const png = await sharp(px, { raw: { width: ancho, height: alto, channels: 4 } }).png().toBuffer();
    const salida = await normalizarImagenFirma(png);
    expect(await estaVacia(salida)).toBe(false);
    const alfa = (await sharp(salida).ensureAlpha().stats()).channels[3];
    expect(alfa.max).toBe(255);
  });

  it('una imagen casi toda tinta (sin papel claro que domine) no se borra', async () => {
    const oscura = await sharp({ create: { width: 300, height: 200, channels: 3, background: '#1d2a6b' } })
      .composite([{ input: { create: { width: 40, height: 40, channels: 3, background: '#ffffff' } }, left: 10, top: 10 }])
      .png()
      .toBuffer();
    expect(await estaVacia(await normalizarImagenFirma(oscura))).toBe(false);
  });

  it('un archivo que no es imagen → 400 con un mensaje para el usuario', async () => {
    await expect(normalizarImagenFirma(Buffer.from('no soy una imagen'))).rejects.toThrow(BadRequestException);
  });

  describe('subir', () => {
    const svc = new FirmaImagenService({} as any, {} as any);
    it.each([
      ['sin archivo', undefined, /Elegí una imagen/],
      ['más de 5 MB', { buffer: Buffer.alloc(10), size: 6 * 1024 * 1024, mimetype: 'image/png' }, /5 MB/],
      ['un PDF', { buffer: Buffer.alloc(10), size: 10, mimetype: 'application/pdf' }, /PNG, JPG o WEBP/],
    ])('rechaza %s', async (_n, archivo, msg) => {
      await expect(svc.subir(EMP, archivo as any)).rejects.toThrow(msg);
    });
  });

  describe('para el recibo', () => {
    afterEach(() => jest.restoreAllMocks());

    it('sin imagen cargada → null, sin ir a Spaces', async () => {
      const svc = new FirmaImagenService({} as any, {} as any);
      const send = jest.spyOn((svc as any).client, 'send');
      expect(await svc.paraRecibo(null)).toBeNull();
      expect(send).not.toHaveBeenCalled();
    });

    it('la baja una vez y después sale de la caché', async () => {
      const svc = new FirmaImagenService({} as any, {} as any);
      const send = jest
        .spyOn((svc as any).client, 'send')
        .mockResolvedValue({ Body: { transformToByteArray: async () => new Uint8Array([1, 2, 3]) } } as never);
      expect(await svc.paraRecibo('empresas/x/firma.png')).toBe(Buffer.from([1, 2, 3]).toString('base64'));
      expect(await svc.paraRecibo('empresas/x/firma.png')).toBe(Buffer.from([1, 2, 3]).toString('base64'));
      expect(send).toHaveBeenCalledTimes(1);
    });

    it('si Spaces no responde, el recibo sale igual sin la imagen (no lanza)', async () => {
      const svc = new FirmaImagenService({} as any, {} as any);
      jest.spyOn((svc as any).client, 'send').mockRejectedValue(new Error('timeout') as never);
      expect(await svc.paraRecibo('empresas/x/firma.png')).toBeNull();
    });
  });
});

describe('FirmaReciboService.paraRecibo: las dos firmas son independientes', () => {
  const original = { url: envs.firmadorPdfUrl, key: envs.firmadorPdfKey };
  afterEach(() => {
    (envs as any).firmadorPdfUrl = original.url;
    (envs as any).firmadorPdfKey = original.key;
  });
  const servicio = (empresa: object | null) => {
    const prisma: any = { empresas: { findUnique: jest.fn().mockResolvedValue(empresa) } };
    const imagenes: any = { paraRecibo: jest.fn(async (k: string | null) => (k ? 'BASE64' : null)) };
    return { svc: new FirmaReciboService(prisma, imagenes), prisma, imagenes };
  };
  const conFirmador = () => {
    (envs as any).firmadorPdfUrl = 'http://127.0.0.1:7100';
    (envs as any).firmadorPdfKey = 'k'.repeat(40);
  };

  it('solo la imagen', async () => {
    conFirmador();
    const { svc } = servicio({ ruc: '80000001', dv: '5', recibo_firma_digital: false, recibo_firma_imagen_key: 'empresas/x/f.png' });
    expect(await svc.paraRecibo(EMP)).toEqual({ firmante: null, imagen: 'BASE64' });
  });

  it('las dos', async () => {
    conFirmador();
    const { svc } = servicio({ ruc: '80000001', dv: '5', recibo_firma_digital: true, recibo_firma_imagen_key: 'empresas/x/f.png' });
    expect(await svc.paraRecibo(EMP)).toEqual({ firmante: { ruc: '80000001', dv: '5' }, imagen: 'BASE64' });
  });

  it('la imagen va aunque el servidor no tenga firmador', async () => {
    (envs as any).firmadorPdfUrl = '';
    const { svc } = servicio({ ruc: '80000001', dv: '5', recibo_firma_digital: true, recibo_firma_imagen_key: 'empresas/x/f.png' });
    expect(await svc.paraRecibo(EMP)).toEqual({ firmante: null, imagen: 'BASE64' });
  });

  it('el ticket no lleva ninguna (ni consulta la empresa)', async () => {
    conFirmador();
    const { svc, prisma } = servicio({ ruc: '80000001', dv: '5', recibo_firma_digital: true, recibo_firma_imagen_key: 'k' });
    expect(await svc.paraRecibo(EMP, 'ticket')).toEqual({ firmante: null, imagen: null });
    expect(prisma.empresas.findUnique).not.toHaveBeenCalled();
  });
});
