import { BadRequestException } from '@nestjs/common';
import { CobrosService } from './cobros.service';

/**
 * `createFromDistribucion` (ERP y app del cobrador) recibe `cliente_id` y, por
 * separado, `cuota_ids`/`factura_ids`. Si no se verifica que sean del mismo
 * cliente, se puede armar un cobro a nombre de A con las cuotas de B (y saltear
 * así un bloqueo que B tenga). `create()` ya lo verificaba para sus detalles;
 * la distribución lo verifica antes de calcular nada.
 */
describe('CobrosService.createFromDistribucion — cuotas y facturas del cliente', () => {
  const CUOTAS = [
    { id: 'qa1', factura_cab: { id: 'fa', cliente_id: 'A', empresa_id: 'E' } },
    { id: 'qa2', factura_cab: { id: 'fa', cliente_id: 'A', empresa_id: 'E' } },
    { id: 'qb1', factura_cab: { id: 'fb', cliente_id: 'B', empresa_id: 'E' } },
    { id: 'qx1', factura_cab: { id: 'fx', cliente_id: 'A', empresa_id: 'OTRA' } },
  ];
  const FACTURAS = [
    { id: 'fa', cliente_id: 'A', empresa_id: 'E' },
    { id: 'fb', cliente_id: 'B', empresa_id: 'E' },
  ];
  const coincide = (obj: any, where: any) =>
    Object.entries(where ?? {}).every(([k, v]: [string, any]) => {
      if (v && typeof v === 'object' && 'in' in v) return v.in.includes(obj[k]);
      if (v && typeof v === 'object') return coincide(obj[k], v);
      return obj[k] === v;
    });

  const crear = () => {
    const service = Object.create(CobrosService.prototype) as any;
    service.logger = { warn: jest.fn(), log: jest.fn(), error: jest.fn() };
    service.prisma = {
      factura_cuotas: { findMany: jest.fn(async ({ where }: any) => CUOTAS.filter((c) => coincide(c, where))) },
      factura_cab: { findMany: jest.fn(async ({ where }: any) => FACTURAS.filter((f) => coincide(f, where))) },
    };
    // Corta el flujo apenas pasa la verificación: lo que sigue no es de este test.
    service.previewDistribucion = jest.fn(async () => {
      throw new Error('SIGUE_AL_PREVIEW');
    });
    return service;
  };
  const dto = (cuota_ids: string[], factura_ids?: string[]) =>
    ({ cuota_ids, factura_ids, monto_recibido: 1000, medio_pago_id: 'mp' }) as any;
  const llamar = (s: any, clienteId: string, d: any) =>
    s.createFromDistribucion(d, 'suc', clienteId, null, 'u', 'E');

  it('cliente A con una cuota del cliente B → 400 y no calcula nada', async () => {
    const s = crear();
    await expect(llamar(s, 'A', dto(['qa1', 'qb1']))).rejects.toThrow(BadRequestException);
    await expect(llamar(s, 'A', dto(['qa1', 'qb1']))).rejects.toThrow('no pertenecen al cliente');
    expect(s.previewDistribucion).not.toHaveBeenCalled();
  });

  it('cliente A con una factura (solo interés) del cliente B → 400', async () => {
    const s = crear();
    await expect(llamar(s, 'A', dto([], ['fb']))).rejects.toThrow(BadRequestException);
    expect(s.previewDistribucion).not.toHaveBeenCalled();
  });

  it('cuota del mismo cliente pero de otra empresa → 400', async () => {
    const s = crear();
    await expect(llamar(s, 'A', dto(['qx1']))).rejects.toThrow(BadRequestException);
  });

  it('datos coherentes (cuotas y facturas de A, ids repetidos incluidos) → sigue al preview como antes', async () => {
    const s = crear();
    await expect(llamar(s, 'A', dto(['qa1', 'qa2', 'qa1'], ['fa']))).rejects.toThrow('SIGUE_AL_PREVIEW');
    expect(s.previewDistribucion).toHaveBeenCalledTimes(1);
  });
});
