import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
import { claveGeneracionCatalogo } from 'src/ecommerce/catalogo-cache';
import { ProductoPrecioDto } from './dto/actualizar-precios-productos.dto';
import { ActualizarProductoListaDto } from './dto/actualizar-producto-lista.dto';
import { ListaPreciosService } from './lista-precios.service';

/** Lo que P2 necesita de listas: buscador, Final del motor, candado de regla, mínimo contra máximo, asignaciones, auditoría y tienda. */
const LISTA = {
  id: 'l1',
  nombre: 'Lista',
  moneda: 'PYG',
  redondeo_activo: false,
  redondeo_tipo: 'normal',
  redondeo_decimales: 0,
  aplica_descuento_general: false,
  aplica_recargo_general: false,
  descuento_porcentaje: 0,
  recargo_porcentaje: 0,
};

const filaBase = (extra: any = {}) => ({
  id: 'f1',
  lista_precios_id: 'l1',
  producto_id: 'p1',
  precio_base: '70000.0000',
  descuento_porcentaje: '0.00',
  recargo_porcentaje: '0.00',
  precio_minimo: null,
  precio_maximo: null,
  descuento_maximo_pct: null,
  origen_precio: 'lista',
  regla_precio_id: null,
  ...extra,
});

interface Config {
  lista?: any;
  fila?: any;
  filas?: any[];
  privilegios?: string[];
  addonActivo?: boolean;
  tipoEmpresa?: string | null;
  principal?: string;
}

const crear = (c: Config = {}) => {
  const fila = c.fila === undefined ? filaBase() : c.fila;
  const filasTabla = {
    findFirst: jest.fn().mockResolvedValue(fila),
    findMany: jest.fn().mockResolvedValue(c.filas ?? (fila ? [fila] : [])),
    count: jest.fn().mockResolvedValue((c.filas ?? (fila ? [fila] : [])).length),
    update: jest.fn().mockImplementation(({ data }) => Promise.resolve({ ...fila, ...data, productos: { descripcion: 'Anchoas' } })),
    create: jest.fn().mockImplementation(({ data }) => Promise.resolve({ id: 'nueva', ...data })),
    deleteMany: jest.fn().mockResolvedValue({ count: 1 }),
    updateMany: jest.fn().mockResolvedValue({ count: 1 }),
  };
  const asignaciones = {
    findFirst: jest.fn().mockResolvedValue(null),
    create: jest.fn().mockImplementation(({ data }) => Promise.resolve({ id: 'a1', ...data })),
    updateMany: jest.fn().mockResolvedValue({ count: 1 }),
  };
  const prisma: any = {
    lista_precios: { findFirst: jest.fn().mockResolvedValue(c.lista ?? LISTA), findUnique: jest.fn().mockResolvedValue({ nombre: 'Lista', codigo: 'L' }) },
    lista_precios_productos: filasTabla,
    lista_precios_asignaciones: asignaciones,
    productos: { findMany: jest.fn().mockResolvedValue([{ id: 'p1' }]) },
    empresa_monedas: { findFirst: jest.fn().mockResolvedValue({ moneda: { codigo: c.principal ?? 'PYG' } }) },
    empresas: { findUnique: jest.fn().mockResolvedValue({ type: c.tipoEmpresa ?? null }) },
    usuario: { findUnique: jest.fn().mockResolvedValue({ is_superadmin: false }) },
    perfiles_privilegios: { findMany: jest.fn().mockResolvedValue((c.privilegios ?? []).map((codigo) => ({ privilegios: { codigo } }))) },
    privilegios: { findMany: jest.fn().mockResolvedValue([{ codigo: 'INV_RGP_PRECIO_EDITAR', submodulos: { id: 's1', codigo: 'INV_REGLAS_PRECIO', es_addon: true } }]) },
    suscripcion_submodulos: { findMany: jest.fn().mockResolvedValue(c.addonActivo === false ? [] : [{ submodulo_id: 's1' }]) },
    clientes: { findFirst: jest.fn().mockResolvedValue({ id: 'c1', lista_precios_id: null }), updateMany: jest.fn().mockResolvedValue({ count: 1 }) },
    zonas_cobranza: { findFirst: jest.fn().mockResolvedValue({ id: 'z1', nombre: 'Norte' }), findMany: jest.fn().mockResolvedValue([{ id: 'z1', nombre: 'Norte' }]) },
  };
  prisma.$transaction = jest.fn((fn: any) => fn(prisma));
  const service = Object.create(ListaPreciosService.prototype) as ListaPreciosService;
  const audit = { log: jest.fn().mockResolvedValue(undefined) };
  const cache = { set: jest.fn().mockResolvedValue(undefined) };
  Object.assign(service as any, { prisma, auditService: audit, cache, logger: { log: jest.fn(), error: jest.fn() } });
  return { service, prisma, audit, cache, filas: filasTabla, asignaciones };
};

const CON_OVERRIDE = ['INV_RGP_PRECIO_EDITAR'];
const sinPermiso = { status: 403, response: expect.objectContaining({ codigo: 'PRECIO_DE_REGLA_SIN_PERMISO' }) };
const codigo = (c: string, extra: any = {}) => ({ response: expect.objectContaining({ codigo: c, ...extra }) });

describe('ListaPreciosService · P2', () => {
  describe('obtenerProductosLista', () => {
    const fila = (extra: any = {}) => filaBase({ productos: { id: 'p1', cod_producto: '015', descripcion: 'Anchoas', unidad_medida_id: null, precio: '65000' }, ...extra });

    it('q filtra por código o descripción, insensible', async () => {
      const { service, filas } = crear({ filas: [] });
      await service.obtenerProductosLista('l1', 1, 20, 'e1', { q: ' ANCHOA ' });
      expect(filas.findMany.mock.calls[0][0].where.productos.OR).toEqual([
        { cod_producto: { contains: 'ANCHOA', mode: 'insensitive' } },
        { descripcion: { contains: 'ANCHOA', mode: 'insensitive' } },
      ]);
      expect(filas.count.mock.calls[0][0].where.productos.OR).toHaveLength(2);
    });

    it('productoIds devuelve las filas de esos productos en cualquier página', async () => {
      const { service, filas } = crear({ filas: [] });
      await service.obtenerProductosLista('l1', 1, 20, 'e1', { productoIds: ['p1', 'p2'] });
      expect(filas.findMany.mock.calls[0][0].where.producto_id.in).toEqual(['p1', 'p2']);
    });

    it('limit 5000 queda en 200', async () => {
      const { service, filas } = crear({ filas: [] });
      const r = await service.obtenerProductosLista('l1', 1, 5000, 'e1');
      expect(filas.findMany.mock.calls[0][0].take).toBe(200);
      expect(r.limit).toBe(200);
    });

    it('ordena por fecha_creacion desc e id', async () => {
      const { service, filas } = crear({ filas: [] });
      await service.obtenerProductosLista('l1', 1, 20, 'e1');
      expect(filas.findMany.mock.calls[0][0].orderBy).toEqual([{ fecha_creacion: 'desc' }, { id: 'asc' }]);
    });

    it('trae productos.precio en el select', async () => {
      const { service, filas } = crear({ filas: [] });
      await service.obtenerProductosLista('l1', 1, 20, 'e1');
      expect(filas.findMany.mock.calls[0][0].include.productos.select.precio).toBe(true);
    });

    const SUPERIOR = { redondeo_activo: true, redondeo_tipo: 'superior', redondeo_decimales: 0 };
    it.each([
      ['{base 100000, d 10}', {}, { precio_base: 100000, descuento_porcentaje: 10 }, 90000],
      ['{base 10000, r 7.78, superior, 0 decimales}', SUPERIOR, { precio_base: 10000, recargo_porcentaje: 7.78 }, 10778],
      ['{base 100000, d 50, mínimo 60000}', {}, { precio_base: 100000, descuento_porcentaje: 50, precio_minimo: 60000 }, 60000],
      ['{base 100000, r 50, máximo 120000}', {}, { precio_base: 100000, recargo_porcentaje: 50, precio_maximo: 120000 }, 120000],
      ['{base 12.5, d 10, USD, sin redondeo}', { moneda: 'USD' }, { precio_base: 12.5, descuento_porcentaje: 10 }, 11.25],
    ])('precio_final es el del motor: %s', async (_nombre, lista, datos, esperado) => {
      const { service } = crear({ lista: { ...LISTA, ...lista }, filas: [fila(datos)] });
      const r = await service.obtenerProductosLista('l1', 1, 20, 'e1');
      expect(r.data[0].precio_final).toBe(esperado);
      expect(r.data[0].productos.cod_producto).toBe('015');
      expect(r.data[0].precio_base).toBe((datos as any).precio_base);
    });

    it('en una lista en otra moneda, sin precio propio, no toma el precio del producto (está en la principal)', async () => {
      const { service } = crear({ lista: { ...LISTA, moneda: 'USD' }, filas: [fila({ precio_base: 0 })] });
      expect((await service.obtenerProductosLista('l1', 1, 20, 'e1')).data[0].precio_final).toBe(0);
    });
  });

  describe('mínimo contra máximo', () => {
    const minimoMayor = { status: 400, response: expect.objectContaining({ codigo: 'PRECIO_MINIMO_MAYOR_MAXIMO', campo: 'precio_minimo' }) };

    it('actualizarProductoLista: mínimo mayor que máximo da PRECIO_MINIMO_MAYOR_MAXIMO con campo precio_minimo', async () => {
      const { service, filas } = crear();
      await expect(service.actualizarProductoLista('l1', 'f1', { precio_minimo: 90, precio_maximo: 80 }, 'e1', 'u1')).rejects.toMatchObject(minimoMayor);
      expect(filas.update).not.toHaveBeenCalled();
    });

    it('solo trae mínimo mayor que el máximo guardado, también', async () => {
      const { service, filas } = crear({ fila: filaBase({ precio_maximo: '80.0000' }) });
      await expect(service.actualizarProductoLista('l1', 'f1', { precio_minimo: 90 }, 'e1', 'u1')).rejects.toMatchObject(minimoMayor);
      expect(filas.update).not.toHaveBeenCalled();
    });

    it('vaciar el mínimo con el máximo guardado menor no da error', async () => {
      const { service, filas } = crear({ fila: filaBase({ precio_minimo: '90.0000', precio_maximo: '80.0000' }) });
      await service.actualizarProductoLista('l1', 'f1', { precio_minimo: null }, 'e1', 'u1');
      expect(filas.update.mock.calls[0][0].data.precio_minimo).toBeNull();
    });

    it('actualizarPreciosProductos: también, y no escribe nada', async () => {
      const { service, filas } = crear({ fila: filaBase({ precio_maximo: '80.0000' }) });
      await expect(service.actualizarPreciosProductos('l1', [{ productoId: 'p1', precioBase: 100, precioMinimo: 90 }], 'u1', 'e1')).rejects.toMatchObject(minimoMayor);
      expect(filas.update).not.toHaveBeenCalled();
      expect(filas.create).not.toHaveBeenCalled();
    });
  });

  describe('candado de regla', () => {
    const deRegla = (extra: any = {}) => filaBase({ origen_precio: 'regla', regla_precio_id: 'r1', ...extra });

    it('sin override, cambia precio_base: 403 (ruta producto) y update no se llama', async () => {
      const { service, filas } = crear({ fila: deRegla() });
      await expect(service.actualizarProductoLista('l1', 'f1', { precio_base: 80000 }, 'e1', 'u1')).rejects.toMatchObject(sinPermiso);
      expect(filas.update).not.toHaveBeenCalled();
    });

    it('lo mismo por PUT /precios', async () => {
      const { service, filas } = crear({ fila: deRegla() });
      await expect(service.actualizarPreciosProductos('l1', [{ productoId: 'p1', precioBase: 80000 }], 'u1', 'e1')).rejects.toMatchObject(sinPermiso);
      expect(filas.update).not.toHaveBeenCalled();
    });

    it.each(['descuento_porcentaje', 'recargo_porcentaje', 'precio_minimo', 'precio_maximo'])('sin override, cambia %s: 403', async (campo) => {
      const { service } = crear({ fila: deRegla() });
      await expect(service.actualizarProductoLista('l1', 'f1', { [campo]: 5 } as any, 'e1', 'u1')).rejects.toMatchObject(sinPermiso);
    });

    it('con override pasa a manual y regla_precio_id null', async () => {
      const { service, filas } = crear({ fila: deRegla(), privilegios: CON_OVERRIDE });
      await service.actualizarProductoLista('l1', 'f1', { precio_base: 80000 }, 'e1', 'u1');
      expect(filas.update.mock.calls[0][0].data).toMatchObject({ precio_base: 80000, origen_precio: 'manual', regla_precio_id: null });
    });

    it('con override por PUT /precios, también', async () => {
      const { service, filas } = crear({ fila: deRegla(), privilegios: CON_OVERRIDE });
      await service.actualizarPreciosProductos('l1', [{ productoId: 'p1', precioBase: 80000 }], 'u1', 'e1');
      expect(filas.update.mock.calls[0][0].data).toMatchObject({ origen_precio: 'manual', regla_precio_id: null });
    });

    it('sin override, cambia solo el tope: pasa y sigue en regla', async () => {
      const { service, filas } = crear({ fila: deRegla() });
      await service.actualizarProductoLista('l1', 'f1', { descuento_maximo_pct: 15 }, 'e1', 'u1');
      const data = filas.update.mock.calls[0][0].data;
      expect(data.descuento_maximo_pct).toBe(15);
      expect(data.origen_precio).toBeUndefined();
      expect(data.regla_precio_id).toBeUndefined();
    });

    it('manda el mismo precio_base: sigue en regla y regla_precio_id no se toca', async () => {
      const { service, filas } = crear({ fila: deRegla() });
      await service.actualizarProductoLista('l1', 'f1', { precio_base: 70000, precio_minimo: null, descuento_maximo_pct: 12 }, 'e1', 'u1');
      const data = filas.update.mock.calls[0][0].data;
      expect(data.origen_precio).toBeUndefined();
      expect(data.regla_precio_id).toBeUndefined();
    });

    it('por PUT /precios con el mismo precio, tampoco', async () => {
      const { service, filas } = crear({ fila: deRegla() });
      await service.actualizarPreciosProductos('l1', [{ productoId: 'p1', precioBase: 70000, descuentoMaximoPct: 12 }], 'u1', 'e1');
      const data = filas.update.mock.calls[0][0].data;
      expect(data.origen_precio).toBeUndefined();
      expect(data.regla_precio_id).toBeUndefined();
    });

    it('addon no contratado con el privilegio: 403 igual', async () => {
      const { service, filas } = crear({ fila: deRegla(), privilegios: CON_OVERRIDE, addonActivo: false });
      await expect(service.actualizarProductoLista('l1', 'f1', { precio_base: 80000 }, 'e1', 'u1')).rejects.toMatchObject(sinPermiso);
      expect(filas.update).not.toHaveBeenCalled();
    });

    it('holding sin el addon, con el privilegio: pasa, como en el guard', async () => {
      const { service, filas } = crear({ fila: deRegla(), privilegios: CON_OVERRIDE, addonActivo: false, tipoEmpresa: 'holding' });
      await service.actualizarProductoLista('l1', 'f1', { precio_base: 80000 }, 'e1', 'u1');
      expect(filas.update).toHaveBeenCalled();
    });

    it('un privilegio con active false no abre el candado', async () => {
      const { service, prisma, filas } = crear({ fila: deRegla() });
      // La base tiene el privilegio pero apagado: el mock responde como la base, según lo que se le pida.
      const guardados = [{ active: false, privilegios: { codigo: 'INV_RGP_PRECIO_EDITAR' } }];
      prisma.perfiles_privilegios.findMany.mockImplementation(({ where }: any) =>
        Promise.resolve(guardados.filter((f) => where?.active === undefined || f.active === where.active)),
      );
      await expect(service.actualizarProductoLista('l1', 'f1', { precio_base: 80000 }, 'e1', 'u1')).rejects.toMatchObject(sinPermiso);
      expect(filas.update).not.toHaveBeenCalled();
    });

    it('una fila de lista no pide override', async () => {
      const { service, filas, prisma } = crear();
      await service.actualizarProductoLista('l1', 'f1', { precio_base: 80000 }, 'e1', 'u1');
      expect(filas.update.mock.calls[0][0].data).toMatchObject({ origen_precio: 'lista', regla_precio_id: null });
      expect(prisma.perfiles_privilegios.findMany).not.toHaveBeenCalled();
    });

    it('quitar una fila de regla sin override: 403 y no borra', async () => {
      const { service, filas } = crear({ fila: deRegla() });
      await expect(service.eliminarProductoLista('l1', 'f1', 'u1', 'e1')).rejects.toMatchObject(sinPermiso);
      expect(filas.deleteMany).not.toHaveBeenCalled();
    });

    it('quitar una fila de regla con override: borra', async () => {
      const { service, filas } = crear({ fila: deRegla(), privilegios: CON_OVERRIDE });
      await service.eliminarProductoLista('l1', 'f1', 'u1', 'e1');
      expect(filas.deleteMany).toHaveBeenCalled();
    });

    it('descuento masivo que alcanza una fila de regla sin override: 403 y no escribe', async () => {
      const { service, filas } = crear();
      filas.count.mockResolvedValue(1);
      await expect(service.aplicarDescuentoMasivo('l1', 5, {}, 'e1', 'u1')).rejects.toMatchObject(sinPermiso);
      expect(filas.count.mock.calls[0][0].where).toMatchObject({ lista_precios_id: 'l1', origen_precio: 'regla' });
      expect(filas.updateMany).not.toHaveBeenCalled();
    });

    it('descuento masivo sin filas de regla: escribe', async () => {
      const { service, filas } = crear();
      filas.count.mockResolvedValue(0);
      await service.aplicarDescuentoMasivo('l1', 5, {}, 'e1', 'u1');
      expect(filas.updateMany).toHaveBeenCalled();
    });
  });

  describe('actualizarPreciosProductos', () => {
    it('corre en $transaction, con 60 s', async () => {
      const { service, prisma } = crear();
      await service.actualizarPreciosProductos('l1', [{ productoId: 'p1', precioBase: 100 }], 'u1', 'e1');
      expect(prisma.$transaction).toHaveBeenCalledTimes(1);
      expect(prisma.$transaction.mock.calls[0][1]).toEqual({ timeout: 60_000 });
    });

    it('lee las existentes con un solo findMany', async () => {
      const { service, filas } = crear();
      await service.actualizarPreciosProductos('l1', [{ productoId: 'p1', precioBase: 100 }], 'u1', 'e1');
      expect(filas.findMany).toHaveBeenCalledTimes(1);
      expect(filas.findFirst).not.toHaveBeenCalled();
    });

    it('update sin descuentoPorcentaje no lo toca', async () => {
      const { service, filas } = crear();
      await service.actualizarPreciosProductos('l1', [{ productoId: 'p1', precioBase: 100 }], 'u1', 'e1');
      const data = filas.update.mock.calls[0][0].data;
      expect(data.descuento_porcentaje).toBeUndefined();
      expect(data.recargo_porcentaje).toBeUndefined();
    });

    it('update con descuento 0 lo escribe', async () => {
      const { service, filas } = crear();
      await service.actualizarPreciosProductos('l1', [{ productoId: 'p1', precioBase: 100, descuentoPorcentaje: 0 }], 'u1', 'e1');
      expect(filas.update.mock.calls[0][0].data.descuento_porcentaje).toBe(0);
    });

    it('create sin descuento queda 0', async () => {
      const { service, filas } = crear({ filas: [] });
      await service.actualizarPreciosProductos('l1', [{ productoId: 'p1', precioBase: 100 }], 'u1', 'e1');
      expect(filas.create.mock.calls[0][0].data).toMatchObject({ descuento_porcentaje: 0, recargo_porcentaje: 0, origen_precio: 'lista' });
    });

    it('el mismo producto dos veces en el cuerpo no crea dos filas', async () => {
      const { service, filas } = crear({ filas: [] });
      await service.actualizarPreciosProductos(
        'l1',
        [
          { productoId: 'p1', precioBase: 100 },
          { productoId: 'p1', precioBase: 200 },
        ],
        'u1',
        'e1',
      );
      expect(filas.create).toHaveBeenCalledTimes(1);
      expect(filas.update).toHaveBeenCalledTimes(1);
    });

    it('productos de otra empresa: PRODUCTOS_NO_ENCONTRADOS', async () => {
      const { service, prisma } = crear();
      prisma.productos.findMany.mockResolvedValue([]);
      await expect(service.actualizarPreciosProductos('l1', [{ productoId: 'p1', precioBase: 100 }], 'u1', 'e1')).rejects.toMatchObject({
        status: 404,
        ...codigo('PRODUCTOS_NO_ENCONTRADOS'),
      });
    });
  });

  it('fila que ya no está: PRODUCTO_LISTA_NO_ENCONTRADO, al editar y al quitar', async () => {
    const { service } = crear({ fila: null });
    const esperado = { status: 404, ...codigo('PRODUCTO_LISTA_NO_ENCONTRADO') };
    await expect(service.actualizarProductoLista('l1', 'f1', { precio_base: 1 }, 'e1', 'u1')).rejects.toMatchObject(esperado);
    await expect(service.eliminarProductoLista('l1', 'f1', 'u1', 'e1')).rejects.toMatchObject(esperado);
  });

  describe('asignaciones', () => {
    it('asignar zona repetida activa no crea', async () => {
      const { service, asignaciones } = crear();
      asignaciones.findFirst.mockResolvedValue({ id: 'a0' });
      await expect(service.asignarListaPrecios('l1', [{ tipoEntidad: 'zona', zonaId: 'z1' }], 'e1', 'u1')).resolves.toEqual([]);
      expect(asignaciones.findFirst.mock.calls[0][0].where).toMatchObject({ tipo_entidad: 'zona', zona_id: 'z1', activa: true });
      expect(asignaciones.create).toHaveBeenCalledTimes(0);
    });

    it('cliente con la lista en su ficha no crea', async () => {
      const { service, prisma, asignaciones } = crear();
      prisma.clientes.findFirst.mockResolvedValue({ id: 'c1', lista_precios_id: 'l1' });
      await expect(service.asignarListaPrecios('l1', [{ tipoEntidad: 'cliente', entidadId: 'c1' }], 'e1', 'u1')).resolves.toEqual([]);
      expect(asignaciones.create).toHaveBeenCalledTimes(0);
    });

    it('fin antes de inicio da ASIGNACION_FECHAS_INVALIDAS con campo fechaFin', async () => {
      const { service, asignaciones } = crear();
      await expect(
        service.asignarListaPrecios('l1', [{ tipoEntidad: 'cliente', entidadId: 'c1', fechaInicio: '2026-11-10', fechaFin: '2026-11-09' }], 'e1', 'u1'),
      ).rejects.toMatchObject({ status: 400, ...codigo('ASIGNACION_FECHAS_INVALIDAS', { campo: 'fechaFin' }) });
      expect(asignaciones.create).not.toHaveBeenCalled();
    });

    it.each([
      ['inicio', { fechaInicio: '2026-13-45' }, 'fechaInicio'],
      ['fin', { fechaInicio: '2026-11-10', fechaFin: 'no-es-fecha' }, 'fechaFin'],
    ])('fecha de %s inválida: 400 ASIGNACION_FECHAS_INVALIDAS, no 500', async (_n, fechas, campo) => {
      const { service, asignaciones } = crear();
      await expect(service.asignarListaPrecios('l1', [{ tipoEntidad: 'cliente', entidadId: 'c1', ...fechas }], 'e1', 'u1')).rejects.toMatchObject({
        status: 400,
        ...codigo('ASIGNACION_FECHAS_INVALIDAS', { campo }),
      });
      expect(asignaciones.create).not.toHaveBeenCalled();
    });

    it('fin igual a inicio vale', async () => {
      const { service, asignaciones } = crear();
      await service.asignarListaPrecios('l1', [{ tipoEntidad: 'cliente', entidadId: 'c1', fechaInicio: '2026-11-10', fechaFin: '2026-11-10' }], 'e1', 'u1');
      expect(asignaciones.create).toHaveBeenCalledTimes(1);
    });

    it('tipo que no es cliente ni zona: ASIGNACION_TIPO_INVALIDO', async () => {
      await expect(crear().service.asignarListaPrecios('l1', [{ tipoEntidad: 'canal' }], 'e1')).rejects.toMatchObject({
        status: 400,
        ...codigo('ASIGNACION_TIPO_INVALIDO', { campo: 'tipoEntidad' }),
      });
    });

    it('cliente de otra empresa: ASIGNACION_CLIENTE_INVALIDO', async () => {
      const { service, prisma } = crear();
      prisma.clientes.findFirst.mockResolvedValue(null);
      await expect(service.asignarListaPrecios('l1', [{ tipoEntidad: 'cliente', entidadId: 'c1' }], 'e1')).rejects.toMatchObject({
        status: 404,
        ...codigo('ASIGNACION_CLIENTE_INVALIDO', { campo: 'entidadId' }),
      });
    });

    it('zona fuera del catálogo: ASIGNACION_ZONA_REQUERIDA', async () => {
      const { service, prisma } = crear();
      prisma.zonas_cobranza.findFirst.mockResolvedValue(null);
      await expect(service.asignarListaPrecios('l1', [{ tipoEntidad: 'zona', zonaId: 'z9' }], 'e1')).rejects.toMatchObject({
        status: 400,
        ...codigo('ASIGNACION_ZONA_REQUERIDA', { campo: 'zonaId' }),
      });
    });

    it('ya quitada: ASIGNACION_NO_ENCONTRADA, de la tabla y de la ficha', async () => {
      const { service, prisma, asignaciones, audit } = crear();
      asignaciones.updateMany.mockResolvedValue({ count: 0 });
      prisma.clientes.updateMany.mockResolvedValue({ count: 0 });
      const esperado = { status: 404, ...codigo('ASIGNACION_NO_ENCONTRADA') };
      await expect(service.eliminarAsignacionLista('l1', 'a1', 'e1', 'u1')).rejects.toMatchObject(esperado);
      await expect(service.eliminarAsignacionLista('l1', 'fk_c1', 'e1', 'u1')).rejects.toMatchObject(esperado);
      expect(audit.log).not.toHaveBeenCalled();
    });

    it('zonas: solo las activas de la empresa', async () => {
      const { service, prisma } = crear();
      await expect(service.obtenerZonasParaAsignar('e1')).resolves.toEqual([{ id: 'z1', nombre: 'Norte' }]);
      const consulta = prisma.zonas_cobranza.findMany.mock.calls[0][0];
      expect(consulta.where).toEqual({ empresa_id: 'e1', active: true });
      expect(consulta.select).toEqual({ id: true, nombre: true });
    });
  });

  describe('auditan', () => {
    it('editar un precio', async () => {
      const { service, audit } = crear();
      await service.actualizarProductoLista('l1', 'f1', { precio_base: 80000 }, 'e1', 'u1');
      expect(audit.log).toHaveBeenCalledWith(
        expect.objectContaining({
          action: 'UPDATE',
          user_id: 'u1',
          old_value: expect.objectContaining({ precio_base: 70000 }),
          new_value: expect.objectContaining({ precio_base: 80000 }),
        }),
      );
    });

    it('asignar', async () => {
      const { service, audit } = crear();
      await service.asignarListaPrecios('l1', [{ tipoEntidad: 'zona', zonaId: 'z1' }], 'e1', 'u1');
      expect(audit.log).toHaveBeenCalledWith(expect.objectContaining({ action: 'CREATE', user_id: 'u1', entity_id: 'l1' }));
    });

    it('asignar sin crear nada, no', async () => {
      const { service, audit, asignaciones } = crear();
      asignaciones.findFirst.mockResolvedValue({ id: 'a0' });
      await service.asignarListaPrecios('l1', [{ tipoEntidad: 'zona', zonaId: 'z1' }], 'e1', 'u1');
      expect(audit.log).not.toHaveBeenCalled();
    });

    it('quitar, de la tabla y de la ficha', async () => {
      const { service, audit } = crear();
      await service.eliminarAsignacionLista('l1', 'a1', 'e1', 'u1');
      await service.eliminarAsignacionLista('l1', 'fk_c1', 'e1', 'u1');
      expect(audit.log).toHaveBeenCalledTimes(2);
      expect(audit.log).toHaveBeenCalledWith(expect.objectContaining({ action: 'DELETE', user_id: 'u1', entity_id: 'a1' }));
      expect(audit.log).toHaveBeenCalledWith(expect.objectContaining({ action: 'DELETE', entity_id: 'fk_c1' }));
    });
  });

  describe('invalidan la tienda', () => {
    const acciones: [string, (s: ListaPreciosService) => Promise<unknown>][] = [
      ['agregar', (s) => s.actualizarPreciosProductos('l1', [{ productoId: 'p1', precioBase: 100 }], 'u1', 'e1')],
      ['editar', (s) => s.actualizarProductoLista('l1', 'f1', { precio_base: 80000 }, 'e1', 'u1')],
      ['quitar', (s) => s.eliminarProductoLista('l1', 'f1', 'u1', 'e1')],
    ];

    it.each(acciones)('%s', async (_n, accion) => {
      const { service, cache } = crear();
      await accion(service);
      expect(cache.set).toHaveBeenCalledWith(claveGeneracionCatalogo('e1'), expect.any(Number), expect.any(Number));
    });

    it.each(acciones)('un fallo de cache.set no rompe: %s', async (_n, accion) => {
      const { service, cache } = crear();
      cache.set.mockRejectedValue(new Error('redis caído'));
      await expect(accion(service)).resolves.toBeDefined();
    });
  });

  it('obtenerPreciosProducto: lista conserva redondeo_tipo', async () => {
    const { service, filas, prisma } = crear();
    prisma.productos.findFirst = jest.fn().mockResolvedValue({ precio: 65000 });
    filas.findMany.mockResolvedValue([
      filaBase({
        precio_base: 10000,
        recargo_porcentaje: 7.78,
        regla_precio: null,
        lista_precios: { ...LISTA, redondeo_activo: true, redondeo_tipo: 'superior', redondeo_decimales: 0 },
      }),
    ]);
    const [fila] = await service.obtenerPreciosProducto('p1', 'e1');
    expect(fila.lista).toMatchObject({ redondeo_activo: true, redondeo_tipo: 'superior', redondeo_decimales: 0 });
    expect((fila.lista as any).aplica_descuento_general).toBeUndefined();
    expect(fila.precio_final).toBe(10778);
  });
});

describe('ficha del producto: respaldo según la moneda de la lista (ola final, O1)', () => {
  it('base 0 en una lista USD da 0; la misma fila en una lista PYG (principal) da el precio del producto', async () => {
    const { service, filas, prisma } = crear();
    prisma.productos.findFirst = jest.fn().mockResolvedValue({ precio: 65000 });
    filas.findMany.mockResolvedValue([
      filaBase({ id: 'fu', precio_base: 0, regla_precio: null, lista_precios: { ...LISTA, id: 'lu', moneda: 'USD' } }),
      filaBase({ id: 'fp', precio_base: 0, regla_precio: null, lista_precios: { ...LISTA } }),
    ]);
    const [usd, pyg] = await service.obtenerPreciosProducto('p1', 'e1');
    expect(usd.precio_final).toBe(0);
    expect(pyg.precio_final).toBe(65000);
  });

  it('con principal USD, la lista USD sí toma el precio del producto y la PYG no', async () => {
    const { service, filas, prisma } = crear({ principal: 'USD' });
    prisma.productos.findFirst = jest.fn().mockResolvedValue({ precio: 12.5 });
    filas.findMany.mockResolvedValue([
      filaBase({ id: 'fu', precio_base: 0, regla_precio: null, lista_precios: { ...LISTA, id: 'lu', moneda: 'USD' } }),
      filaBase({ id: 'fp', precio_base: 0, regla_precio: null, lista_precios: { ...LISTA } }),
    ]);
    const [usd, pyg] = await service.obtenerPreciosProducto('p1', 'e1');
    expect(usd.precio_final).toBe(12.5);
    expect(pyg.precio_final).toBe(0);
  });
});

describe('DTO de precios', () => {
  const opciones = { whitelist: true, forbidNonWhitelisted: true };
  const props = async (clase: any, cuerpo: any) => (await validate(plainToInstance(clase, cuerpo) as object, opciones)).map((e) => e.property);

  it('ActualizarProductoListaDto: descuento_porcentaje 120 no pasa', async () => {
    await expect(props(ActualizarProductoListaDto, { descuento_porcentaje: 120 })).resolves.toEqual(['descuento_porcentaje']);
  });

  it('precio_minimo null pasa', async () => {
    await expect(props(ActualizarProductoListaDto, { precio_minimo: null })).resolves.toEqual([]);
  });

  it('precio_base null no pasa: la columna no admite vacío', async () => {
    await expect(props(ActualizarProductoListaDto, { precio_base: null })).resolves.toEqual(['precio_base']);
  });

  it('campo desconocido no pasa con forbidNonWhitelisted', async () => {
    await expect(props(ActualizarProductoListaDto, { origen_precio: 'lista' })).resolves.toEqual(['origen_precio']);
  });

  it('admite lo que mandan los dos llamadores', async () => {
    await expect(
      props(ActualizarProductoListaDto, {
        precio_base: 1,
        descuento_porcentaje: 0,
        recargo_porcentaje: 0,
        precio_minimo: null,
        precio_maximo: null,
        descuento_maximo_pct: null,
        permite_cuotas: true,
        cuotas_maximas: 12,
      }),
    ).resolves.toEqual([]);
  });

  it('ProductoPrecioDto: recargoPorcentaje 120 y descuentoMaximoPct 120 no pasan', async () => {
    const base = { productoId: '7f3c2d4e-6d6a-4a0b-9b1f-2a3b4c5d6e7f', precioBase: 1 };
    await expect(props(ProductoPrecioDto, { ...base, recargoPorcentaje: 120 })).resolves.toEqual(['recargoPorcentaje']);
    await expect(props(ProductoPrecioDto, { ...base, descuentoMaximoPct: 120 })).resolves.toEqual(['descuentoMaximoPct']);
    await expect(props(ProductoPrecioDto, { ...base, descuentoPorcentaje: 120 })).resolves.toEqual(['descuentoPorcentaje']);
  });
});
