import { envs } from 'src/config/envs';
import { BadRequestException } from '@nestjs/common';
import { cabecerasFirma, FirmaReciboService, validarActivacionFirmaRecibos } from './firma-recibo.service';

const EMP = '11111111-1111-1111-1111-111111111111';
const PDF = Buffer.from('%PDF-1.7 recibo');

function servicio(empresa: { ruc: string; dv: string; recibo_firma_digital: boolean } | null) {
  const prisma: any = { empresas: { findUnique: jest.fn().mockResolvedValue(empresa) } };
  return { svc: new FirmaReciboService(prisma), prisma };
}

const responder = (status: number, cuerpo: Buffer | object) =>
  jest
    .spyOn(global, 'fetch')
    .mockImplementation(() =>
      Promise.resolve(
        Buffer.isBuffer(cuerpo)
          ? new Response(new Uint8Array(cuerpo), { status, headers: { 'content-type': 'application/pdf' } })
          : new Response(JSON.stringify(cuerpo), { status, headers: { 'content-type': 'application/json' } }),
      ),
    );

describe('FirmaReciboService', () => {
  const original = { url: envs.firmadorPdfUrl, key: envs.firmadorPdfKey };
  beforeEach(() => {
    (envs as any).firmadorPdfUrl = 'http://127.0.0.1:7100/';
    (envs as any).firmadorPdfKey = 'k'.repeat(40);
  });
  afterEach(() => {
    (envs as any).firmadorPdfUrl = original.url;
    (envs as any).firmadorPdfKey = original.key;
    jest.restoreAllMocks();
  });

  it('firma sólo si la empresa lo activó, en A4 y con firmador configurado', async () => {
    expect(await servicio({ ruc: '80000001', dv: '5', recibo_firma_digital: true }).svc.firmante(EMP)).toEqual({
      ruc: '80000001',
      dv: '5',
    });
    expect(await servicio({ ruc: '80000001', dv: '5', recibo_firma_digital: false }).svc.firmante(EMP)).toBeNull();
    const { svc, prisma } = servicio({ ruc: '80000001', dv: '5', recibo_firma_digital: true });
    expect(await svc.firmante(EMP, 'ticket')).toBeNull();
    (envs as any).firmadorPdfKey = '';
    expect(await svc.firmante(EMP)).toBeNull();
    expect(prisma.empresas.findUnique).not.toHaveBeenCalled();
  });

  it('llama al firmador con la clave, el RUC y el PDF en crudo, y devuelve el firmado', async () => {
    const f = responder(200, Buffer.from('%PDF firmado'));
    const r = await servicio(null).svc.firmar(PDF, { ruc: '80000001', dv: '5' });
    expect(r).toEqual({ pdf: Buffer.from('%PDF firmado'), estado: 'FIRMADO' });
    const [url, init] = f.mock.calls[0] as [string, RequestInit];
    expect(url).toBe('http://127.0.0.1:7100/api/v1/firmar?ruc=80000001&dv=5');
    expect(init.headers).toMatchObject({ 'Content-Type': 'application/pdf', 'x-firmador-key': 'k'.repeat(40) });
    expect(Buffer.from(init.body as Uint8Array)).toEqual(PDF);
  });

  it('si no puede firmar, el recibo sale igual (el original) con un motivo legible', async () => {
    const { svc } = servicio(null);
    responder(422, { codigo: 'CERTIFICADO_VENCIDO', mensaje: '…' });
    expect(await svc.firmar(PDF, { ruc: '80000001', dv: '5' })).toEqual({
      pdf: PDF,
      estado: 'SIN_FIRMA',
      motivo: 'El certificado digital de la empresa está vencido',
    });
    responder(500, { codigo: 'ERROR_INTERNO' });
    expect((await svc.firmar(PDF, { ruc: '80000001', dv: '5' })).motivo).toBe('No se pudo firmar el recibo');
    jest.spyOn(global, 'fetch').mockRejectedValue(new TypeError('fetch failed'));
    expect(await svc.firmar(PDF, { ruc: '80000001', dv: '5' })).toEqual({
      pdf: PDF,
      estado: 'SIN_FIRMA',
      motivo: 'El servicio de firma digital no responde',
    });
  });

  it('base64 de ida y vuelta', async () => {
    responder(200, Buffer.from('%PDF firmado'));
    const r = await servicio(null).svc.firmarBase64(PDF.toString('base64'), { ruc: '80000001', dv: '5' });
    expect(r).toEqual({ base64: Buffer.from('%PDF firmado').toString('base64'), estado: 'FIRMADO' });
  });

  it('headers: nada si no correspondía firmar; el motivo va codificado', () => {
    expect(cabecerasFirma(undefined)).toEqual({});
    expect(cabecerasFirma({ estado: 'FIRMADO' })).toEqual({ 'X-Firma-Digital': 'FIRMADO' });
    expect(cabecerasFirma({ estado: 'SIN_FIRMA', motivo: 'Certificado vencido ñ' })).toEqual({
      'X-Firma-Digital': 'SIN_FIRMA',
      'X-Firma-Motivo': 'Certificado%20vencido%20%C3%B1',
    });
  });

  it('activarla exige firmador en el servidor y un certificado vigente (el más nuevo)', () => {
    const ahora = new Date('2026-11-13T12:00:00Z');
    const vigente = { fecha_vencimiento: '2027-05-01T00:00:00.000Z' };
    const vencido = { fecha_vencimiento: new Date('2026-11-01T00:00:00Z') };
    expect(() => validarActivacionFirmaRecibos([vigente], true, ahora)).not.toThrow();
    const motivo = (f: () => void) => {
      try {
        f();
        return 'OK';
      } catch (e) {
        expect(e).toBeInstanceOf(BadRequestException);
        return (e as Error).message;
      }
    };
    expect(motivo(() => validarActivacionFirmaRecibos([vigente], false, ahora))).toMatch(/no está disponible/);
    expect(motivo(() => validarActivacionFirmaRecibos([], true, ahora))).toMatch(/certificado digital vigente/);
    expect(motivo(() => validarActivacionFirmaRecibos(undefined, true, ahora))).toMatch(/certificado digital vigente/);
    // Vale el más nuevo: uno viejo vigente no salva a uno nuevo vencido.
    expect(motivo(() => validarActivacionFirmaRecibos([vencido, vigente], true, ahora))).toMatch(/vigente/);
  });
});
