import { Prisma } from '@prisma/client';
import { claveGeneracionCatalogo } from 'src/ecommerce/catalogo-cache';
import { PreciosEngineService } from './precios-engine.service';

const LISTA_PYG = { id: 'l1', empresa_id: 'e1', moneda: 'PYG' };
const LISTA_USD = { id: 'lusd', empresa_id: 'e1', moneda: 'USD' };

const REGLA = {
  id: 'r1',
  empresa_id: 'e1',
  nombre: 'Regla',
  prioridad: 1,
  moneda: 'PYG',
  alcance: 'global',
  categoria_id: null,
  costo_desde: new Prisma.Decimal(1000),
  costo_hasta: null,
  metodo: 'margen_sobre_costo',
  valor: new Prisma.Decimal(40),
  redondeo_activo: true,
  redondeo_tipo: 'superior',
  redondeo_multiplo: new Prisma.Decimal(1000),
  lista_precios_id: 'l1',
  activo: true,
};

const DTO: any = { nombre: 'Nueva', costoDesde: 0, valor: 40, listaPreciosId: 'l1' };

const crear = (c: { lista?: any; regla?: any; principal?: string; privilegios?: string[]; superadmin?: boolean } = {}) => {
  const filas = {
    findFirst: jest.fn().mockResolvedValue(null),
    findMany: jest.fn().mockResolvedValue([]),
    count: jest.fn().mockResolvedValue(0),
    create: jest.fn().mockResolvedValue({}),
    updateMany: jest.fn().mockResolvedValue({ count: 1 }),
  };
  const reglas = {
    findFirst: jest.fn().mockResolvedValue(c.regla === undefined ? REGLA : c.regla),
    findMany: jest.fn().mockResolvedValue([]),
    create: jest.fn().mockImplementation(({ data }) => Promise.resolve({ id: 'r2', ...data })),
    update: jest.fn().mockImplementation(({ data }) => Promise.resolve({ ...REGLA, ...data })),
  };
  const prisma: any = {
    lista_precios: { findFirst: jest.fn().mockResolvedValue(c.lista === undefined ? LISTA_PYG : c.lista) },
    empresa_monedas: { findFirst: jest.fn().mockResolvedValue({ moneda: { codigo: c.principal ?? 'PYG' } }) },
    categorias: { findFirst: jest.fn().mockResolvedValue({ id: 'cat1' }) },
    reglas_precio: reglas,
    lista_precios_productos: filas,
    productos: { count: jest.fn().mockResolvedValue(0), findMany: jest.fn().mockResolvedValue([]), findFirst: jest.fn() },
    usuario: { findUnique: jest.fn().mockResolvedValue({ is_superadmin: !!c.superadmin }) },
    perfiles_privilegios: { findMany: jest.fn().mockResolvedValue((c.privilegios ?? []).map((codigo) => ({ privilegios: { codigo } }))) },
  };
  const audit = { log: jest.fn().mockResolvedValue(undefined) };
  const cache = { set: jest.fn().mockResolvedValue(undefined) };
  const service = new PreciosEngineService(prisma, audit as any, cache as any);
  return { service, prisma, reglas, filas, audit, cache };
};

const conCodigo = (codigo: string, extra: any = {}) => ({ response: expect.objectContaining({ codigo, ...extra }) });

describe('PreciosEngineService · gestión', () => {
  afterEach(() => jest.useRealTimers());

  describe('lista en otra moneda', () => {
    const otraMoneda = { status: 400, ...conCodigo('REGLA_LISTA_OTRA_MONEDA', { campo: 'listaPreciosId' }) };

    it('crear con lista USD (principal PYG): REGLA_LISTA_OTRA_MONEDA y no escribe', async () => {
      const { service, reglas } = crear({ lista: LISTA_USD });
      await expect(service.crear({ ...DTO, listaPreciosId: 'lusd' }, 'e1', 'u1')).rejects.toMatchObject(otraMoneda);
      expect(reglas.create).not.toHaveBeenCalled();
    });

    it('actualizar con lista USD (principal PYG): REGLA_LISTA_OTRA_MONEDA y no escribe', async () => {
      const { service, reglas } = crear({ lista: LISTA_USD });
      await expect(service.actualizar('r1', { listaPreciosId: 'lusd' }, 'e1', 'u1')).rejects.toMatchObject(otraMoneda);
      expect(reglas.update).not.toHaveBeenCalled();
    });

    it('recalcular con lista USD (principal PYG): REGLA_LISTA_OTRA_MONEDA y no escribe', async () => {
      const { service, filas, prisma } = crear({ lista: LISTA_USD });
      await expect(service.recalcularLista({ listaPreciosId: 'lusd' }, 'e1', 'u1')).rejects.toMatchObject(otraMoneda);
      expect(prisma.productos.findMany).not.toHaveBeenCalled();
      expect(filas.create).not.toHaveBeenCalled();
      expect(filas.updateMany).not.toHaveBeenCalled();
    });

    it('editar una regla que ya apunta a una lista USD sin cambiarle la lista: también', async () => {
      const { service, reglas } = crear({ lista: LISTA_USD, regla: { ...REGLA, lista_precios_id: 'lusd' } });
      await expect(service.actualizar('r1', { nombre: 'Otro' }, 'e1', 'u1')).rejects.toMatchObject(otraMoneda);
      expect(reglas.update).not.toHaveBeenCalled();
    });

    it('con principal USD, una lista USD sí se puede', async () => {
      const { service, reglas } = crear({ lista: LISTA_USD, principal: 'USD' });
      await service.crear({ ...DTO, listaPreciosId: 'lusd' }, 'e1', 'u1');
      expect(reglas.create.mock.calls[0][0].data.moneda).toBe('USD');
    });
  });

  it('lista de otra empresa: REGLA_LISTA_INVALIDA', async () => {
    const { service, reglas, prisma } = crear({ lista: null });
    await expect(service.crear(DTO, 'e1', 'u1')).rejects.toMatchObject({ status: 400, ...conCodigo('REGLA_LISTA_INVALIDA', { campo: 'listaPreciosId' }) });
    expect(prisma.lista_precios.findFirst.mock.calls[0][0].where).toEqual({ id: 'l1', empresa_id: 'e1' });
    expect(reglas.create).not.toHaveBeenCalled();
  });

  it('crear manda moneda USD en el cuerpo y lista PYG: guarda PYG', async () => {
    const { service, reglas } = crear();
    await service.crear({ ...DTO, moneda: 'USD' }, 'e1', 'u1');
    expect(reglas.create.mock.calls[0][0].data.moneda).toBe('PYG');
  });

  it('actualizar manda moneda USD en el cuerpo: queda la de la lista', async () => {
    const { service, reglas } = crear();
    await service.actualizar('r1', { moneda: 'USD' }, 'e1', 'u1');
    expect(reglas.update.mock.calls[0][0].data.moneda).toBe('PYG');
  });

  describe('alcance categoria', () => {
    const invalida = { status: 400, ...conCodigo('REGLA_CATEGORIA_INVALIDA', { campo: 'categoriaId' }) };

    it('con categoría de otra empresa: REGLA_CATEGORIA_INVALIDA', async () => {
      const { service, reglas, prisma } = crear();
      prisma.categorias.findFirst.mockResolvedValue(null);
      await expect(service.crear({ ...DTO, alcance: 'categoria', categoriaId: 'ajena' }, 'e1', 'u1')).rejects.toMatchObject(invalida);
      expect(prisma.categorias.findFirst.mock.calls[0][0].where).toEqual({ id: 'ajena', empresa_id: 'e1' });
      expect(reglas.create).not.toHaveBeenCalled();
    });

    it('sin id: REGLA_CATEGORIA_INVALIDA', async () => {
      const { service, reglas } = crear();
      await expect(service.crear({ ...DTO, alcance: 'categoria' }, 'e1', 'u1')).rejects.toMatchObject(invalida);
      expect(reglas.create).not.toHaveBeenCalled();
    });

    it('al editar, cambiar a categoría sin id tampoco', async () => {
      const { service, reglas } = crear();
      await expect(service.actualizar('r1', { alcance: 'categoria' }, 'e1', 'u1')).rejects.toMatchObject(invalida);
      expect(reglas.update).not.toHaveBeenCalled();
    });

    it('con categoría de la empresa, la guarda', async () => {
      const { service, reglas } = crear();
      await service.crear({ ...DTO, alcance: 'categoria', categoriaId: 'cat1' }, 'e1', 'u1');
      expect(reglas.create.mock.calls[0][0].data).toMatchObject({ alcance: 'categoria', categoria_id: 'cat1' });
    });

    it('editar a global la desconecta', async () => {
      const { service, reglas } = crear({ regla: { ...REGLA, alcance: 'categoria', categoria_id: 'cat1' } });
      await service.actualizar('r1', { alcance: 'global' }, 'e1', 'u1');
      expect(reglas.update.mock.calls[0][0].data.categoria).toEqual({ disconnect: true });
    });
  });

  describe('validaciones', () => {
    it.each([0, -5])('valor %s: REGLA_VALOR_INVALIDO', async (valor) => {
      const { service, reglas } = crear();
      await expect(service.crear({ ...DTO, valor }, 'e1', 'u1')).rejects.toMatchObject({ status: 400, ...conCodigo('REGLA_VALOR_INVALIDO', { campo: 'valor' }) });
      expect(reglas.create).not.toHaveBeenCalled();
    });

    it('hasta ≤ desde: REGLA_RANGO_INVALIDO', async () => {
      const { service } = crear();
      await expect(service.crear({ ...DTO, costoDesde: 100, costoHasta: 100 }, 'e1', 'u1')).rejects.toMatchObject({
        status: 400,
        ...conCodigo('REGLA_RANGO_INVALIDO', { campo: 'costoHasta' }),
      });
    });

    it('solo trae costoHasta, menor que el costo desde guardado: REGLA_RANGO_INVALIDO', async () => {
      const { service, reglas } = crear();
      await expect(service.actualizar('r1', { costoHasta: 500 }, 'e1', 'u1')).rejects.toMatchObject(conCodigo('REGLA_RANGO_INVALIDO'));
      expect(reglas.update).not.toHaveBeenCalled();
    });

    it('solo trae costoDesde, mayor que el hasta guardado: también', async () => {
      const { service } = crear({ regla: { ...REGLA, costo_hasta: new Prisma.Decimal(2000) } });
      await expect(service.actualizar('r1', { costoDesde: 3000 }, 'e1', 'u1')).rejects.toMatchObject(conCodigo('REGLA_RANGO_INVALIDO'));
    });

    it('margen sobre precio 100: REGLA_MARGEN_INVALIDO', async () => {
      const { service } = crear();
      await expect(service.crear({ ...DTO, metodo: 'margen_sobre_precio', valor: 100 }, 'e1', 'u1')).rejects.toMatchObject({
        status: 400,
        ...conCodigo('REGLA_MARGEN_INVALIDO', { campo: 'valor' }),
      });
    });

    it('inexistente: REGLA_NO_ENCONTRADA', async () => {
      const { service } = crear({ regla: null });
      await expect(service.actualizar('r9', {}, 'e1', 'u1')).rejects.toMatchObject({ status: 404, ...conCodigo('REGLA_NO_ENCONTRADA') });
    });
  });

  it('actualizar con costoHasta null deja null', async () => {
    const { service, reglas } = crear({ regla: { ...REGLA, costo_hasta: new Prisma.Decimal(5000) } });
    await service.actualizar('r1', { costoHasta: null }, 'e1', 'u1');
    expect(reglas.update.mock.calls[0][0].data.costo_hasta).toBeNull();
  });

  it('actualizar sin costoHasta no lo toca', async () => {
    const { service, reglas } = crear({ regla: { ...REGLA, costo_hasta: new Prisma.Decimal(5000) } });
    await service.actualizar('r1', { nombre: 'Otro' }, 'e1', 'u1');
    expect(reglas.update.mock.calls[0][0].data.costo_hasta).toBeUndefined();
  });

  describe('vigencia en hora de Asunción', () => {
    const LAS_22 = '2026-05-13T01:00:00Z';
    const DIA = '2026-05-12T00:00:00.000Z';

    it('calcularPrecio a las 22:00 de Asunción: una regla con fecha_fin de hoy aplica', async () => {
      jest.useFakeTimers({ now: new Date(LAS_22) });
      const { service, reglas, prisma } = crear();
      prisma.productos.findFirst.mockResolvedValue({ precio_costo: 1000, categoria_id: null, categoria: null });
      await service.calcularPrecio('p1', 'l1', 'e1');
      const where = reglas.findMany.mock.calls[0][0].where;
      expect(where.fecha_inicio.lte.toISOString()).toBe(DIA);
      expect(where.AND[1].OR[1].fecha_fin.gte.toISOString()).toBe(DIA);
    });

    it('alta sin fecha a esa hora guarda 2026-05-12', async () => {
      jest.useFakeTimers({ now: new Date(LAS_22) });
      const { service, reglas } = crear();
      await service.crear(DTO, 'e1', 'u1');
      expect(reglas.create.mock.calls[0][0].data.fecha_inicio.toISOString()).toBe(DIA);
    });
  });

  describe('aplicarRegla', () => {
    const aplicar = (costo: number, regla: any) =>
      (crear().service as any).aplicarRegla(costo, { redondeo_activo: true, redondeo_tipo: 'superior', redondeo_multiplo: 1000, metodo: 'margen_sobre_costo', ...regla });

    it.each([
      ['costo 100000 margen 40 superior 1000', 100000, { valor: 40 }, 140000],
      ['costo 100001', 100001, { valor: 40 }, 141000],
      ['margen_sobre_precio 100000/20', 100000, { metodo: 'margen_sobre_precio', valor: 20 }, 125000],
      ['precio_fijo 99000', 5, { metodo: 'precio_fijo', valor: 99000 }, 99000],
      ['normal 125499 a 1000', 125499, { metodo: 'precio_fijo', valor: 125499, redondeo_tipo: 'normal' }, 125000],
      ['inferior 125999 a 1000', 125999, { metodo: 'precio_fijo', valor: 125999, redondeo_tipo: 'inferior' }, 125000],
      ['220000 margen 10 superior 1000: sin el error de coma flotante', 220000, { valor: 10 }, 242000],
    ])('%s', (_n, costo, regla, esperado) => {
      expect(aplicar(costo, regla)).toBe(esperado);
    });
  });

  it('generarGrillaCuotas: sin el error de coma flotante en la cuota', async () => {
    const { service, prisma } = crear();
    prisma.lista_precios_productos.findFirst.mockResolvedValue({ precio_base: 220000 });
    prisma.lista_precios.findUnique = jest.fn().mockResolvedValue({ moneda: 'PYG' });
    prisma.productos.findUnique = jest.fn().mockResolvedValue({ categoria_id: null, categoria: null });
    prisma.planes_cuotas = {
      findMany: jest
        .fn()
        .mockResolvedValue([{ id: 'pl', nombre: '1', cantidad_cuotas: 1, tasa_interes: 10, categoria_id: null, precio_producto_desde: null, precio_producto_hasta: null }]),
    };
    const cuotas = { findFirst: jest.fn().mockResolvedValue(null), create: jest.fn().mockResolvedValue({}), findMany: jest.fn().mockResolvedValue([]), updateMany: jest.fn() };
    prisma.producto_precio_cuota = cuotas;
    await service.generarGrillaCuotas('p1', 'l1', 'e1', 'u1');
    expect(cuotas.create.mock.calls[0][0].data.monto_cuota).toBe(242000);
  });

  describe('previsualizar', () => {
    const PRODUCTO = { id: 'p1', descripcion: 'Anchoas', cod_producto: '015', precio_costo: new Prisma.Decimal(100000), precio: new Prisma.Decimal(65000) };
    const conMuestra = (filas: any[] = []) => {
      const c = crear();
      c.prisma.productos.count.mockResolvedValue(3);
      c.prisma.productos.findMany.mockResolvedValue([PRODUCTO]);
      c.filas.findMany.mockResolvedValue(filas);
      return c;
    };

    it('excluye costo 0', async () => {
      const { service, prisma } = conMuestra();
      await service.previsualizar('r1', 'e1');
      expect(prisma.productos.count.mock.calls[0][0].where.precio_costo).toEqual({ gt: 0, gte: 1000 });
    });

    it('limit 500 queda en 100', async () => {
      const { service, prisma } = conMuestra();
      await service.previsualizar('r1', 'e1', 500);
      expect(prisma.productos.findMany.mock.calls[0][0].take).toBe(100);
    });

    it('precioActual es el de la lista destino', async () => {
      const { service, filas } = conMuestra([{ producto_id: 'p1', precio_base: new Prisma.Decimal(70000), origen_precio: 'lista' }]);
      const r = await service.previsualizar('r1', 'e1', 20, true);
      expect(filas.findMany.mock.calls[0][0].where).toEqual({ lista_precios_id: 'l1', producto_id: { in: ['p1'] } });
      expect(r.ejemplos[0]).toMatchObject({ precioActual: 70000, precioProducto: 65000, precioSugerido: 140000, origen: 'lista', editadoAMano: false });
    });

    it('precioActual null si no tiene', async () => {
      const { service } = conMuestra();
      const r = await service.previsualizar('r1', 'e1', 20, true);
      expect(r.ejemplos[0]).toMatchObject({ precioActual: null, origen: null, editadoAMano: false });
    });

    it('editadoAMano true con origen manual', async () => {
      const { service } = conMuestra([{ producto_id: 'p1', precio_base: new Prisma.Decimal(70000), origen_precio: 'manual' }]);
      const r = await service.previsualizar('r1', 'e1', 20, true);
      expect(r.ejemplos[0]).toMatchObject({ origen: 'manual', editadoAMano: true });
    });

    it('sin verCosto, precioCosto null', async () => {
      const { service } = conMuestra();
      expect((await service.previsualizar('r1', 'e1', 20, false)).ejemplos[0].precioCosto).toBeNull();
      expect((await service.previsualizar('r1', 'e1', 20, true)).ejemplos[0].precioCosto).toBe(100000);
    });

    it('cuenta los cargados en la lista: «preservar» no los protege', async () => {
      const { service, filas } = conMuestra();
      filas.count.mockResolvedValue(7);
      const r = await service.previsualizar('r1', 'e1');
      expect(r.totalCargadosEnLista).toBe(7);
      expect(filas.count.mock.calls[0][0].where).toMatchObject({ lista_precios_id: 'l1', origen_precio: 'lista' });
      expect(r.totalProductosAfectados).toBe(3);
    });
  });

  describe('puedeVerCosto', () => {
    it('con INV_STK_COSTO_VER, sí; sin él, no', async () => {
      await expect(crear({ privilegios: ['INV_STK_COSTO_VER'] }).service.puedeVerCosto('u1')).resolves.toBe(true);
      await expect(crear().service.puedeVerCosto('u1')).resolves.toBe(false);
    });
  });

  describe('reactivar', () => {
    it('activo true y audita ACTIVATE', async () => {
      const { service, reglas, audit } = crear({ regla: { ...REGLA, activo: false } });
      await service.reactivar('r1', 'e1', 'u1');
      expect(reglas.update.mock.calls[0][0]).toMatchObject({ where: { id: 'r1' }, data: { activo: true } });
      expect(audit.log).toHaveBeenCalledWith(expect.objectContaining({ action: 'ACTIVATE', entity_id: 'r1', user_id: 'u1' }));
    });

    it('de otra empresa: REGLA_NO_ENCONTRADA', async () => {
      const { service, reglas } = crear({ regla: null });
      await expect(service.reactivar('r1', 'otra', 'u1')).rejects.toMatchObject({ status: 404, ...conCodigo('REGLA_NO_ENCONTRADA') });
      expect(reglas.findFirst.mock.calls[0][0].where).toEqual({ id: 'r1', empresa_id: 'otra' });
      expect(reglas.update).not.toHaveBeenCalled();
    });
  });

  describe('recalcular', () => {
    const errorP2002 = () => new Prisma.PrismaClientKnownRequestError('dup', { code: 'P2002', clientVersion: 'x' });
    const CALCULO = { precioCosto: 100, precioSugerido: 140000, reglaAplicadaId: 'r1', reglaAplicadaNombre: 'R', desglose: '' };
    const preparar = (existente: any) => {
      const c = crear();
      c.prisma.productos.findMany.mockResolvedValue([{ id: 'p1' }]);
      c.filas.findFirst.mockResolvedValue(existente);
      jest.spyOn(c.service, 'calcularPrecio').mockResolvedValue(CALCULO);
      return c;
    };
    const DTO_R = { listaPreciosId: 'l1', generarCuotas: false };

    it('corte a mitad y la auditoría también falla: sale el error del corte, no el de la auditoría, y la tienda se invalida', async () => {
      const { service, filas, audit, cache } = preparar(null);
      filas.create.mockRejectedValue(new Error('se cortó la base'));
      audit.log.mockRejectedValue(new Error('auditoría caída'));
      await expect(service.recalcularLista(DTO_R, 'e1', 'u1')).rejects.toThrow('se cortó la base');
      expect(cache.set).toHaveBeenCalled();
    });

    it('corte a mitad y la tienda también falla: sale el error del corte', async () => {
      const { service, filas, cache } = preparar(null);
      filas.create.mockRejectedValue(new Error('se cortó la base'));
      cache.set.mockRejectedValue(new Error('redis caído'));
      await expect(service.recalcularLista(DTO_R, 'e1', 'u1')).rejects.toThrow('se cortó la base');
    });

    it('corrida completa con la auditoría caída: el error se informa, no se traga', async () => {
      const { service, audit } = preparar(null);
      audit.log.mockRejectedValue(new Error('auditoría caída'));
      await expect(service.recalcularLista(DTO_R, 'e1', 'u1')).rejects.toThrow('auditoría caída');
    });

    it('invalida la tienda', async () => {
      const { service, cache } = preparar(null);
      await service.recalcularLista(DTO_R, 'e1', 'u1');
      expect(cache.set).toHaveBeenCalledWith(claveGeneracionCatalogo('e1'), expect.any(Number), expect.any(Number));
    });

    it('una edición a mano entre leer y escribir no se pisa: cuenta como omitido', async () => {
      const { service, filas } = preparar({ id: 'f1', origen_precio: 'regla' });
      filas.updateMany.mockResolvedValue({ count: 0 });
      const r = await service.recalcularLista(DTO_R, 'e1', 'u1');
      expect(filas.updateMany.mock.calls[0][0].where).toEqual({ id: 'f1', origen_precio: { not: 'manual' } });
      expect(r).toMatchObject({ actualizados: 0, omitidos_por_override: 1 });
    });

    it('sin preservar, la escritura no mira el origen', async () => {
      const { service, filas } = preparar({ id: 'f1', origen_precio: 'manual' });
      const r = await service.recalcularLista({ ...DTO_R, preservarOverride: false }, 'e1', 'u1');
      expect(filas.updateMany.mock.calls[0][0].where).toEqual({ id: 'f1' });
      expect(r.actualizados).toBe(1);
    });

    it('una fila quitada a mitad de camino no corta la corrida', async () => {
      const { service, filas } = preparar({ id: 'f1', origen_precio: 'lista' });
      filas.updateMany.mockResolvedValue({ count: 0 });
      await expect(service.recalcularLista({ ...DTO_R, preservarOverride: false }, 'e1', 'u1')).resolves.toMatchObject({ omitidos_por_override: 1 });
    });

    it('otra corrida a la vez (P2002): reintenta como update', async () => {
      const { service, filas } = preparar(null);
      filas.create.mockRejectedValue(errorP2002());
      const r = await service.recalcularLista(DTO_R, 'e1', 'u1');
      expect(filas.updateMany.mock.calls[0][0].where).toEqual({ lista_precios_id: 'l1', producto_id: 'p1', origen_precio: { not: 'manual' } });
      expect(r.actualizados).toBe(1);
    });

    it('un corte a mitad de camino audita lo parcial e invalida igual', async () => {
      const { service, prisma, audit, cache, filas } = preparar(null);
      prisma.productos.findMany.mockResolvedValue([{ id: 'p1' }, { id: 'p2' }]);
      filas.create.mockResolvedValueOnce({}).mockRejectedValueOnce(new Error('se cortó la base'));
      await expect(service.recalcularLista(DTO_R, 'e1', 'u1')).rejects.toThrow('se cortó la base');
      expect(audit.log).toHaveBeenCalledWith(
        expect.objectContaining({ descripcion: expect.stringContaining('interrumpido'), new_value: expect.objectContaining({ actualizados: 1, total_evaluados: 2 }) }),
      );
      expect(cache.set).toHaveBeenCalled();
    });

    it('editado a mano ya leído: omitido sin calcular', async () => {
      const { service, filas } = preparar({ id: 'f1', origen_precio: 'manual' });
      const r = await service.recalcularLista(DTO_R, 'e1', 'u1');
      expect(service.calcularPrecio).not.toHaveBeenCalled();
      expect(filas.updateMany).not.toHaveBeenCalled();
      expect(r.omitidos_por_override).toBe(1);
    });
  });
});
