import { claveGeneracionCatalogo } from 'src/ecommerce/catalogo-cache';
import { crearServicio, EMPRESA, filaOferta, ID, REF } from './ofertas-test-utils';

const ALTA = { nombre: 'Promo', tipo: 'descuento_porcentaje', valor: 10, fecha_inicio: '2026-11-05T11:00:00.000Z', fecha_fin: '2026-11-30T11:00:00.000Z' } as any;
const MONTO = { ...ALTA, tipo: 'descuento_monto', valor: 5000 };
const err = (codigo: string, campo?: string) => ({ status: 400, response: { codigo, ...(campo && { campo }) } });

describe('Ofertas: escritura', () => {
  describe('moneda (B4)', () => {
    it('monto sin moneda → 400 MONEDA_REQUERIDA, campo moneda', async () => {
      const { service, prisma } = crearServicio();
      await expect(service.create(MONTO, EMPRESA, 'u1')).rejects.toMatchObject(err('MONEDA_REQUERIDA', 'moneda'));
      expect(prisma.ofertas.create).not.toHaveBeenCalled();
    });
    it('% con moneda USD guarda moneda null', async () => {
      const { service, prisma } = crearServicio();
      await service.create({ ...ALTA, moneda: 'USD' }, EMPRESA, 'u1');
      expect(prisma.ofertas.create.mock.calls[0][0].data.moneda).toBeNull();
    });
    it('monto en USD guarda USD', async () => {
      const { service, prisma } = crearServicio();
      await service.create({ ...MONTO, valor: 100.5, moneda: 'USD' }, EMPRESA, 'u1');
      expect(prisma.ofertas.create.mock.calls[0][0].data).toMatchObject({ moneda: 'USD', valor: 100.5 });
    });
    it('pasar de monto a % deja moneda null', async () => {
      const { service, tx } = crearServicio({ oferta: filaOferta({ tipo: 'descuento_monto', valor: 5000, moneda: 'PYG' }) });
      await service.update(ID, { tipo: 'descuento_porcentaje', valor: 10 } as any, EMPRESA, 'u1');
      expect(tx.ofertas.update.mock.calls[0][0].data.moneda).toBeNull();
    });
    it('pasar de % a monto sin moneda → MONEDA_REQUERIDA', async () => {
      const { service } = crearServicio();
      await expect(service.update(ID, { tipo: 'descuento_monto', valor: 5000 } as any, EMPRESA, 'u1')).rejects.toMatchObject(err('MONEDA_REQUERIDA', 'moneda'));
    });
    it('editar el nombre de un monto conserva su moneda sin consultar', async () => {
      const { service, prisma, tx } = crearServicio({ oferta: filaOferta({ tipo: 'descuento_monto', valor: 5000, moneda: 'PYG' }) });
      await service.update(ID, { nombre: 'Otro' } as any, EMPRESA, 'u1');
      expect(tx.ofertas.update.mock.calls[0][0].data.moneda).toBe('PYG');
      expect(prisma.empresa_monedas.findMany).not.toHaveBeenCalled();
    });
    it('monto PYG 100.5 → 400 VALOR_CON_DECIMALES', async () => {
      const { service } = crearServicio();
      await expect(service.create({ ...MONTO, valor: 100.5, moneda: 'PYG' }, EMPRESA, 'u1')).rejects.toMatchObject(err('VALOR_CON_DECIMALES', 'valor'));
    });
    it('moneda no habilitada → 400 MONEDA_NO_HABILITADA', async () => {
      const { service } = crearServicio({ monedas: ['PYG'] });
      await expect(service.create({ ...MONTO, moneda: 'EUR' }, EMPRESA, 'u1')).rejects.toMatchObject(err('MONEDA_NO_HABILITADA', 'moneda'));
    });
  });

  describe('validaciones (D13)', () => {
    it('update con valor 0 en monto → 400 VALOR_INVALIDO', async () => {
      const { service } = crearServicio({ oferta: filaOferta({ tipo: 'descuento_monto', valor: 5000, moneda: 'PYG' }) });
      await expect(service.update(ID, { valor: 0 } as any, EMPRESA, 'u1')).rejects.toMatchObject(err('VALOR_INVALIDO', 'valor'));
    });
    it('% 101 → PORCENTAJE_INVALIDO', async () => {
      const { service } = crearServicio();
      await expect(service.create({ ...ALTA, valor: 101 }, EMPRESA, 'u1')).rejects.toMatchObject(err('PORCENTAJE_INVALIDO', 'valor'));
    });
    it('fin igual a inicio → FECHAS_INVALIDAS, campo fecha_fin', async () => {
      const { service } = crearServicio();
      await expect(service.create({ ...ALTA, fecha_fin: ALTA.fecha_inicio }, EMPRESA, 'u1')).rejects.toMatchObject(err('FECHAS_INVALIDAS', 'fecha_fin'));
      await expect(service.update(ID, { fecha_fin: '2026-11-01T11:00:00.000Z' } as any, EMPRESA, 'u1')).rejects.toMatchObject(err('FECHAS_INVALIDAS', 'fecha_fin'));
    });
    it('nombre "   " → NOMBRE_REQUERIDO', async () => {
      const { service } = crearServicio();
      await expect(service.create({ ...ALTA, nombre: '   ' }, EMPRESA, 'u1')).rejects.toMatchObject(err('NOMBRE_REQUERIDO', 'nombre'));
      await expect(service.update(ID, { nombre: '   ' } as any, EMPRESA, 'u1')).rejects.toMatchObject(err('NOMBRE_REQUERIDO', 'nombre'));
    });
    it('aplicaciones [] → APLICACION_REQUERIDA, en alta y edición', async () => {
      const { service } = crearServicio();
      await expect(service.create({ ...ALTA, aplicaciones: [] }, EMPRESA, 'u1')).rejects.toMatchObject(err('APLICACION_REQUERIDA'));
      await expect(service.update(ID, { aplicaciones: [] } as any, EMPRESA, 'u1')).rejects.toMatchObject(err('APLICACION_REQUERIDA'));
    });
    it('categoria sin referencia → REFERENCIA_REQUERIDA', async () => {
      const { service } = crearServicio();
      await expect(service.create({ ...ALTA, aplicaciones: [{ aplica_a: 'categoria' }] }, EMPRESA, 'u1')).rejects.toMatchObject(err('REFERENCIA_REQUERIDA', 'referencia_id'));
    });
    it('sin aplicaciones en el alta queda «todos»', async () => {
      const { service, prisma } = crearServicio();
      await service.create(ALTA, EMPRESA, 'u1');
      expect(prisma.ofertas.create.mock.calls[0][0].data.oferta_aplicacion.create).toEqual([{ aplica_a: 'todos', referencia_id: null, excluir: false }]);
    });
  });

  describe('edición', () => {
    it('update sin aplicaciones no borra las existentes', async () => {
      const { service, tx } = crearServicio();
      await service.update(ID, { nombre: 'Otro' } as any, EMPRESA, 'u1');
      expect(tx.oferta_aplicacion.deleteMany).not.toHaveBeenCalled();
    });
    it('con aplicaciones las reemplaza', async () => {
      const { service, tx } = crearServicio();
      await service.update(ID, { aplicaciones: [{ aplica_a: 'producto', referencia_id: REF }] } as any, EMPRESA, 'u1');
      expect(tx.oferta_aplicacion.deleteMany).toHaveBeenCalled();
      expect(tx.oferta_aplicacion.createMany.mock.calls[0][0].data).toEqual([{ oferta_id: ID, aplica_a: 'producto', referencia_id: REF, excluir: false }]);
    });
    it('descripcion null la borra', async () => {
      const { service, tx } = crearServicio();
      await service.update(ID, { descripcion: null } as any, EMPRESA, 'u1');
      expect(tx.ofertas.update.mock.calls[0][0].data.descripcion).toBeNull();
    });
    it('sucursal_ids [] las vacía', async () => {
      const { service, tx } = crearServicio();
      await service.update(ID, { sucursal_ids: [] } as any, EMPRESA, 'u1');
      expect(tx.oferta_sucursales.deleteMany).toHaveBeenCalledWith({ where: { oferta_id: ID } });
      expect(tx.oferta_sucursales.createMany).not.toHaveBeenCalled();
    });
  });

  describe('caché de la tienda (B10) y auditoría', () => {
    const clave = claveGeneracionCatalogo(EMPRESA);
    it.each([
      ['alta', (s: any) => s.create(ALTA, EMPRESA, 'u1')],
      ['edición', (s: any) => s.update(ID, { nombre: 'X' }, EMPRESA, 'u1')],
      ['activar', (s: any) => s.toggleActive(ID, EMPRESA, 'u1')],
      ['eliminar', (s: any) => s.remove(ID, EMPRESA, 'u1')],
    ])('%s invalida el caché de la tienda', async (_, llamar) => {
      const { service, cache } = crearServicio();
      await llamar(service);
      expect(cache.set).toHaveBeenCalledWith(clave, expect.any(Number), expect.any(Number));
    });
    it('un fallo de validación no', async () => {
      const { service, cache } = crearServicio();
      await expect(service.create({ ...ALTA, valor: 0 }, EMPRESA, 'u1')).rejects.toBeDefined();
      expect(cache.set).not.toHaveBeenCalled();
    });
    it('la auditoría lleva moneda', async () => {
      const { service, audit } = crearServicio();
      await service.create({ ...MONTO, moneda: 'USD', valor: 5 }, EMPRESA, 'u1');
      expect(audit.log.mock.calls[0][0].new_value).toMatchObject({ moneda: 'USD' });
    });
  });
});
