import { Prisma } from '@prisma/client';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
import { claveGeneracionCatalogo } from 'src/ecommerce/catalogo-cache';
import { CreateProductoPrecioCuotaDto } from './dto/create-producto-precio-cuota.dto';
import { ProductoPrecioCuotasService } from './producto-precio-cuotas.service';

const CUOTA = {
  id: 'q1',
  empresa_id: 'e1',
  producto_id: 'p1',
  nombre: '3 CUOTAS',
  cant_cuotas: 3,
  monto_cuota: '1000000.0000',
  monto_total: '3000000.0000',
  cuota_inicial: null,
  descuento_porcentaje: '0.00',
  moneda: 'PYG',
  activo: true,
};
const DTO = { producto_id: 'p1', nombre: '3 CUOTAS', cant_cuotas: 3, monto_cuota: 1000000 };

const errorPrisma = (code: string) => new Prisma.PrismaClientKnownRequestError(code, { code, clientVersion: 'x' });

const crear = (cuota: any = CUOTA, principal = 'PYG') => {
  const tabla = {
    findFirst: jest.fn().mockResolvedValue(cuota),
    create: jest.fn().mockImplementation(({ data }) => Promise.resolve({ id: 'q2', ...data })),
    update: jest.fn().mockImplementation(({ data }) => Promise.resolve({ ...cuota, ...data })),
    delete: jest.fn().mockResolvedValue(cuota),
  };
  const prisma: any = {
    producto_precio_cuota: tabla,
    productos: { findFirst: jest.fn().mockResolvedValue({ id: 'p1', descripcion: 'Producto' }) },
    empresa_monedas: {
      findFirst: jest.fn().mockResolvedValue({ moneda: { codigo: principal } }),
      findMany: jest.fn().mockResolvedValue([{ moneda: { codigo: principal } }, { moneda: { codigo: 'PYG' } }]),
    },
    factura_det: { count: jest.fn().mockResolvedValue(0) },
    solicitud_credito_det: { count: jest.fn().mockResolvedValue(0) },
  };
  const audit = { log: jest.fn().mockResolvedValue(undefined) };
  const cache = { set: jest.fn().mockResolvedValue(undefined) };
  const service = new ProductoPrecioCuotasService(prisma, audit as any, cache as any);
  return { service, prisma, tabla, audit, cache };
};

const noEncontrada = { status: 404, response: expect.objectContaining({ codigo: 'CUOTA_NO_ENCONTRADA' }) };

describe('ProductoPrecioCuotasService', () => {
  describe('cuota de otra empresa: 404 CUOTA_NO_ENCONTRADA', () => {
    const acciones: [string, (s: ProductoPrecioCuotasService) => Promise<unknown>][] = [
      ['update', (s) => s.update('q1', { nombre: 'X' }, 'otra', 'u1')],
      ['remove', (s) => s.remove('q1', 'otra', 'u1')],
      ['toggleActivo', (s) => s.toggleActivo('q1', 'otra', 'u1')],
      ['findOne', (s) => s.findOne('q1', 'otra')],
    ];

    it.each(acciones)('%s', async (_n, accion) => {
      const { service, tabla } = crear(null);
      await expect(accion(service)).rejects.toMatchObject(noEncontrada);
      expect(tabla.findFirst.mock.calls[0][0].where).toEqual({ id: 'q1', empresa_id: 'otra' });
      expect(tabla.update).not.toHaveBeenCalled();
      expect(tabla.delete).not.toHaveBeenCalled();
    });
  });

  it('create con producto de otra empresa: CUOTA_PRODUCTO_INVALIDO', async () => {
    const { service, prisma, tabla } = crear();
    prisma.productos.findFirst.mockResolvedValue(null);
    await expect(service.create(DTO, 'e1', 'u1')).rejects.toMatchObject({ status: 404, response: expect.objectContaining({ codigo: 'CUOTA_PRODUCTO_INVALIDO' }) });
    expect(prisma.productos.findFirst.mock.calls[0][0].where).toEqual({ id: 'p1', empresa_id: 'e1' });
    expect(tabla.create).not.toHaveBeenCalled();
  });

  describe('remove', () => {
    const enUso = { status: 409, response: expect.objectContaining({ codigo: 'CUOTA_EN_USO' }) };

    it('con factura: 409 CUOTA_EN_USO y delete no se llama', async () => {
      const { service, prisma, tabla } = crear();
      prisma.factura_det.count.mockResolvedValue(1);
      await expect(service.remove('q1', 'e1', 'u1')).rejects.toMatchObject(enUso);
      expect(prisma.factura_det.count.mock.calls[0][0].where).toEqual({ producto_precio_cuota_id: 'q1' });
      expect(tabla.delete).not.toHaveBeenCalled();
    });

    it('con solicitud: 409 CUOTA_EN_USO y delete no se llama', async () => {
      const { service, prisma, tabla } = crear();
      prisma.solicitud_credito_det.count.mockResolvedValue(1);
      await expect(service.remove('q1', 'e1', 'u1')).rejects.toMatchObject(enUso);
      expect(tabla.delete).not.toHaveBeenCalled();
    });

    it('una solicitud que entra entre el conteo y el borrado (P2003): CUOTA_EN_USO, no 500', async () => {
      const { service, tabla } = crear();
      tabla.delete.mockRejectedValue(errorPrisma('P2003'));
      await expect(service.remove('q1', 'e1', 'u1')).rejects.toMatchObject(enUso);
    });

    it('sin uso: delete', async () => {
      const { service, tabla } = crear();
      await service.remove('q1', 'e1', 'u1');
      expect(tabla.delete).toHaveBeenCalledWith({ where: { id: 'q1' } });
    });
  });

  describe('nombre repetido', () => {
    const duplicado = { status: 409, response: expect.objectContaining({ codigo: 'CUOTA_NOMBRE_DUPLICADO', campo: 'nombre' }) };

    it('create con P2002: 409 CUOTA_NOMBRE_DUPLICADO campo nombre', async () => {
      const { service, tabla } = crear();
      tabla.create.mockRejectedValue(errorPrisma('P2002'));
      await expect(service.create(DTO, 'e1', 'u1')).rejects.toMatchObject(duplicado);
    });

    it('update, igual', async () => {
      const { service, tabla } = crear();
      tabla.update.mockRejectedValue(errorPrisma('P2002'));
      await expect(service.update('q1', { nombre: 'X' }, 'e1', 'u1')).rejects.toMatchObject(duplicado);
    });

    it('otro error no se disfraza', async () => {
      const { service, tabla } = crear();
      const raro = new Error('caído');
      tabla.create.mockRejectedValue(raro);
      await expect(service.create(DTO, 'e1', 'u1')).rejects.toBe(raro);
    });
  });

  describe('moneda', () => {
    it('create sin moneda toma la principal', async () => {
      const { service, tabla } = crear(CUOTA, 'USD');
      await service.create(DTO, 'e1', 'u1');
      expect(tabla.create.mock.calls[0][0].data.moneda).toBe('USD');
    });

    it('con moneda, esa', async () => {
      const { service, tabla } = crear(CUOTA, 'USD');
      await service.create({ ...DTO, moneda: 'PYG' }, 'e1', 'u1');
      expect(tabla.create.mock.calls[0][0].data.moneda).toBe('PYG');
    });
  });

  it('update con cuota_inicial null la quita', async () => {
    const { service, tabla } = crear();
    await service.update('q1', { cuota_inicial: null }, 'e1', 'u1');
    expect(tabla.update.mock.calls[0][0].data.cuota_inicial).toBeNull();
  });

  it('update recalcula monto_total y cambia el activo', async () => {
    const { service, tabla } = crear();
    await service.update('q1', { monto_cuota: 500000, activo: false }, 'e1', 'u1');
    expect(tabla.update.mock.calls[0][0].data).toMatchObject({ monto_total: 1500000, activo: false });
  });

  describe('auditoría y tienda', () => {
    const acciones: [string, string, (s: ProductoPrecioCuotasService) => Promise<unknown>][] = [
      ['crear', 'CREATE', (s) => s.create(DTO, 'e1', 'u1')],
      ['editar', 'UPDATE', (s) => s.update('q1', { nombre: 'X' }, 'e1', 'u1')],
      ['eliminar', 'DELETE', (s) => s.remove('q1', 'e1', 'u1')],
      ['toggle', 'DEACTIVATE', (s) => s.toggleActivo('q1', 'e1', 'u1')],
    ];

    it.each(acciones)('audita e invalida la tienda: %s', async (_n, action, accion) => {
      const { service, audit, cache } = crear();
      await accion(service);
      expect(audit.log).toHaveBeenCalledWith(expect.objectContaining({ action, empresa_id: 'e1', user_id: 'u1', entity_type: 'producto_precio_cuota' }));
      expect(cache.set).toHaveBeenCalledWith(claveGeneracionCatalogo('e1'), expect.any(Number), expect.any(Number));
    });
  });

  describe('lecturas de la venta', () => {
    it('findByProducto filtra por empresa y trae también las inactivas', async () => {
      const { service, tabla } = crear();
      (tabla as any).findMany = jest.fn().mockResolvedValue([]);
      await service.findByProducto('p1', 'e1');
      expect((tabla as any).findMany.mock.calls[0][0].where).toEqual({ producto_id: 'p1', empresa_id: 'e1' });
    });
  });

  describe('DTO', () => {
    const props = async (cuerpo: any) => (await validate(plainToInstance(CreateProductoPrecioCuotaDto, cuerpo))).map((e) => e.property);
    const base = { producto_id: '7f3c2d4e-6d6a-4a0b-9b1f-2a3b4c5d6e7f', nombre: '3 cuotas', cant_cuotas: 3, monto_cuota: 100 };

    it('el cuerpo normal pasa', async () => {
      await expect(props(base)).resolves.toEqual([]);
    });

    it('nombre de 101 no pasa', async () => {
      await expect(props({ ...base, nombre: 'x'.repeat(101) })).resolves.toEqual(['nombre']);
    });

    it('monto_cuota 0 no pasa', async () => {
      await expect(props({ ...base, monto_cuota: 0 })).resolves.toEqual(['monto_cuota']);
    });

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

    it.each(['dólar', 'US', 'usd1'])('moneda %s no pasa', async (moneda) => {
      await expect(props({ ...base, moneda })).resolves.toEqual(['moneda']);
    });

    it('moneda USD pasa', async () => {
      await expect(props({ ...base, moneda: 'USD' })).resolves.toEqual([]);
    });
  });

  describe('moneda de la cuota: solo las habilitadas (ola final, P2 T1 M4)', () => {
    const habilitadas = (prisma: any, codigos: string[]) => {
      prisma.empresa_monedas.findMany = jest.fn().mockResolvedValue(codigos.map((codigo) => ({ moneda: { codigo } })));
    };

    it('crear con una moneda que la empresa no tiene: MONEDA_NO_HABILITADA y no escribe', async () => {
      const { service, prisma, tabla } = crear();
      habilitadas(prisma, ['PYG']);
      await expect(service.create({ ...DTO, moneda: 'EUR' } as any, 'e1', 'u1')).rejects.toMatchObject({
        status: 400,
        response: expect.objectContaining({ codigo: 'MONEDA_NO_HABILITADA', campo: 'moneda' }),
      });
      expect(tabla.create).not.toHaveBeenCalled();
    });

    it('crear con una habilitada la guarda', async () => {
      const { service, prisma, tabla } = crear();
      habilitadas(prisma, ['PYG', 'USD']);
      await service.create({ ...DTO, moneda: 'USD' } as any, 'e1', 'u1');
      expect(tabla.create.mock.calls[0][0].data.moneda).toBe('USD');
    });

    it('editar a una moneda que la empresa no tiene: MONEDA_NO_HABILITADA y no escribe', async () => {
      const { service, prisma, tabla } = crear();
      habilitadas(prisma, ['PYG']);
      await expect(service.update('q1', { moneda: 'EUR' } as any, 'e1', 'u1')).rejects.toMatchObject({ response: expect.objectContaining({ codigo: 'MONEDA_NO_HABILITADA' }) });
      expect(tabla.update).not.toHaveBeenCalled();
    });

    it('editar manteniendo la moneda que ya tiene no la valida', async () => {
      const { service, prisma, tabla } = crear({ ...CUOTA, moneda: 'EUR' });
      habilitadas(prisma, ['PYG']);
      await service.update('q1', { moneda: 'EUR', nombre: 'X' } as any, 'e1', 'u1');
      expect(tabla.update).toHaveBeenCalled();
    });
  });
});
