import { BadRequestException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { MiddlewareSifenService } from './middleware-sifen.service';

/**
 * Cancelar o inutilizar (ECAN/EINU) una factura cobrada en caja anula la venta:
 * pide la misma autorización de supervisor que «Anular» (antes este camino no
 * pedía nada aunque la anulación local sí).
 */
function crear(opts: { pagosCaja?: number; supervisor?: boolean; consumo?: number } = {}) {
  const service: any = Object.create(MiddlewareSifenService.prototype);
  service.prisma = {
    factura_forma_pagos: { count: jest.fn().mockResolvedValue(opts.pagosCaja ?? 1) },
    usuario: { findUnique: jest.fn().mockResolvedValue({ is_superadmin: false }) },
    perfiles_privilegios: { findFirst: jest.fn().mockResolvedValue(opts.supervisor ? { id: 'pp' } : null) },
    autorizaciones_caja: {
      findFirst: jest.fn().mockResolvedValue(null),
      updateMany: jest.fn().mockResolvedValue({ count: opts.consumo ?? 1 }),
    },
  };
  return service;
}

const token = (payload: Record<string, unknown> = {}) =>
  jest.spyOn(JwtService.prototype, 'verifyAsync').mockResolvedValue({
    tipo: 'autorizacion_caja',
    empresa_id: 'emp-1',
    sub: 'sup-1',
    operacion: 'anulacion',
    autorizacion_id: 'aut-1',
    contexto: { factura_id: 'fac-1' },
    ...payload,
  } as never);

const autorizar = (service: any, tipoEvento: string, tok?: string, tipoDoc = 'factura') =>
  service.autorizarAnulacionPorEvento('emp-1', tipoDoc, tipoEvento, 'fac-1', 'caj-1', tok);

afterEach(() => jest.restoreAllMocks());

describe('Evento SIFEN que anula una venta de caja: autorización de supervisor', () => {
  it.each(['cancelacion', 'inutilizacion'])('%s sin autorización: 403 con el código que abre el PIN', async (evento) => {
    await expect(autorizar(crear(), evento)).rejects.toMatchObject({
      response: expect.objectContaining({ codigo: 'ANULACION_REQUIERE_AUTORIZACION' }),
    });
  });

  it('con el PIN para esa factura: se consume', async () => {
    token();
    const service = crear();
    await autorizar(service, 'cancelacion', 'tok');
    expect(service.prisma.autorizaciones_caja.updateMany).toHaveBeenCalledWith({
      where: { id: 'aut-1', empresa_id: 'emp-1', estado: 'aprobada' },
      data: { estado: 'utilizada' },
    });
    // Busca los pagos en caja de ESA factura y de la empresa.
    expect(service.prisma.factura_forma_pagos.count).toHaveBeenCalledWith({
      where: { factura_cab_id: 'fac-1', sesion_caja_id: { not: null }, factura_cab: { empresa_id: 'emp-1' } },
    });
  });

  it('token ya usado u otra factura: 403', async () => {
    token();
    await expect(autorizar(crear({ consumo: 0 }), 'cancelacion', 'tok')).rejects.toThrow(/ya se usó/);
    jest.restoreAllMocks();
    token({ contexto: { factura_id: 'fac-9' } });
    await expect(autorizar(crear(), 'inutilizacion', 'tok')).rejects.toThrow(/otra factura/);
  });

  it('un supervisor no la necesita; una factura sin pagos en caja tampoco', async () => {
    await expect(autorizar(crear({ supervisor: true }), 'cancelacion')).resolves.toBeUndefined();
    await expect(autorizar(crear({ pagosCaja: 0 }), 'cancelacion')).resolves.toBeUndefined();
  });

  it('nominación y otros documentos no llevan autorización (y no la aceptan)', async () => {
    await expect(autorizar(crear(), 'nominacion')).resolves.toBeUndefined();
    await expect(autorizar(crear(), 'cancelacion', undefined, 'nota_credito')).resolves.toBeUndefined();
    await expect(autorizar(crear(), 'nominacion', 'tok')).rejects.toThrow(BadRequestException);
  });
});
