import { ClientesService } from 'src/clientes/clientes.service';
import { ProductosService } from 'src/productos/productos.service';
import { rubrosFiltroUsuario } from 'src/utils/alcance-rubro';

jest.mock('src/utils/alcance-rubro', () => ({ rubrosFiltroUsuario: jest.fn() }));
beforeEach(() => (rubrosFiltroUsuario as jest.Mock).mockReset().mockResolvedValue(null));

/**
 * `/clientes/search` y `/productos/search`: el texto del usuario va a LIKE escapado (`%`/`_` no son comodines: con
 * `q=%%` antes salía toda la cartera), cortado a 60, y el `limit` con tope (se recorta, no da 400).
 */
const contains = (or: any[]) => or.flatMap((c) => Object.values(c)).filter((v: any) => v?.contains !== undefined || v?.startsWith !== undefined);

describe('ClientesService.search: comodines y topes', () => {
  const crear = () => {
    const service: any = Object.create(ClientesService.prototype);
    const findMany = jest.fn().mockResolvedValue([]);
    service.prisma = { clientes: { findMany } };
    return { service: service as ClientesService, findMany };
  };

  it('escapa % _ y \\ en cada contains', async () => {
    const { service, findMany } = crear();
    await service.search('%_\\', 'emp', 20);
    const or = findMany.mock.calls[0][0].where.personas.OR;
    expect(contains(or).map((v: any) => v.contains)).toEqual(['\\%\\_\\\\', '\\%\\_\\\\', '\\%\\_\\\\']);
  });

  it('limit mayor al tope se recorta a 100; texto cortado a 60', async () => {
    const { service, findMany } = crear();
    await service.search('a'.repeat(200), 'emp', 100000);
    const args = findMany.mock.calls[0][0];
    expect(args.take).toBe(100);
    expect(args.where.personas.OR[0].razon_social.contains).toHaveLength(60);
  });
});

describe('ProductosService.search: comodines y topes', () => {
  const crear = () => {
    const findMany = jest.fn().mockResolvedValue([]);
    const prisma: any = { productos: { findMany } };
    const service = new ProductosService(prisma, { get: () => undefined } as any, {} as any, {} as any, {} as any, {} as any);
    return { service, findMany };
  };

  it('escapa % _ y \\ en contains/startsWith; el equals de presentaciones va sin escapar', async () => {
    const { service, findMany } = crear();
    await service.search('%_\\', 'emp', 20);
    const or = findMany.mock.calls[0][0].where.OR;
    const valores = contains(or).map((v: any) => v.contains ?? v.startsWith);
    expect(valores).toEqual(['\\%\\_\\\\', '\\%\\_\\\\', '\\%\\_\\\\', '\\%\\_\\\\']);
    expect(or[4].producto_presentaciones.some.codigo_barra.equals).toBe('%_\\');
  });

  it('limit se recorta al tope de 50 que ya tenía; texto cortado a 60', async () => {
    const { service, findMany } = crear();
    await service.search('b'.repeat(200), 'emp', 100000);
    const args = findMany.mock.calls[0][0];
    expect(args.take).toBe(50);
    expect(args.where.OR[0].descripcion.contains).toHaveLength(60);
  });
});
