import { BadRequestException, ForbiddenException } from '@nestjs/common';
import { AlertasClienteService } from '../gestiones/alertas-cliente.service';
import { MIOS_LIMITE_MAXIMO, MobileCobrosService } from './mobile-cobros.service';

function armar(motivo: string | null) {
  const cobros: any = {
    createFromDistribucion: jest.fn().mockResolvedValue({ id: 'r1', numero_recibo: '001' }),
    create: jest.fn().mockResolvedValue({ id: 'r1', numero_recibo: '001' }),
    getReciboPrintData: jest.fn().mockResolvedValue({}),
    findAll: jest.fn().mockResolvedValue({ data: [] }),
    verificarCuotasDelCliente: jest.fn().mockResolvedValue(undefined),
  };
  const prisma: any = {
    recibos_cobro: { update: jest.fn() },
    medio_pago: { findFirst: jest.fn().mockResolvedValue({ id: 'mp' }) },
  };
  const vendedores: any = { findCobradorVinculado: jest.fn().mockResolvedValue({ id: 'cob' }) };
  const alertas: any = { motivoBloqueoCobro: jest.fn().mockResolvedValue(motivo) };
  const svc = new MobileCobrosService(cobros, vendedores, prisma, {} as any, {} as any, alertas);
  return { svc, cobros, alertas };
}

const dist: any = { cliente_id: 'cl', cuota_ids: ['q1'], sucursal_id: 's', medio_pago_id: 'mp', monto_recibido: 1 };
const simple: any = { cliente_id: 'cl', imputaciones: [{ factura_cuota_id: 'q1', monto: 1 }], forma_pago: 'EFECTIVO' };

describe('MobileCobrosService · cliente con alerta que bloquea el cobro', () => {
  it('crear-desde-distribucion rechaza con 403 y el motivo, sin cobrar', async () => {
    const { svc, cobros, alertas } = armar('Cliente con demanda judicial. Coordiná con la oficina antes de cobrar.');
    await expect(svc.crearDesdeDistribucion('e', 'u', dist)).rejects.toThrow(ForbiddenException);
    await expect(svc.crearDesdeDistribucion('e', 'u', dist)).rejects.toThrow('demanda judicial');
    expect(alertas.motivoBloqueoCobro).toHaveBeenCalledWith('e', 'cl');
    expect(cobros.createFromDistribucion).not.toHaveBeenCalled();
  });

  it('crear (cobro simple) rechaza con 403 y el motivo, sin cobrar', async () => {
    const { svc, cobros } = armar('Cliente informado a Informconf. Coordiná con la oficina antes de cobrar.');
    await expect(svc.crear('e', 'u', simple)).rejects.toThrow('Informconf');
    expect(cobros.create).not.toHaveBeenCalled();
  });

  it('sin alerta bloqueante cobra normalmente', async () => {
    const { svc, cobros } = armar(null);
    const r = await svc.crearDesdeDistribucion('e', 'u', dist);
    expect(r.cobro_id).toBe('r1');
    expect(cobros.createFromDistribucion).toHaveBeenCalled();
  });
});

describe('MobileCobrosService · cuotas de otro cliente', () => {
  it('verifica que las cuotas sean del cliente ANTES del control de bloqueo', async () => {
    const { svc, cobros, alertas } = armar(null);
    cobros.verificarCuotasDelCliente.mockRejectedValue(
      new BadRequestException('Una o más cuotas no existen o no pertenecen al cliente seleccionado'),
    );
    await expect(svc.crearDesdeDistribucion('e', 'u', dist)).rejects.toThrow(BadRequestException);
    expect(cobros.verificarCuotasDelCliente).toHaveBeenCalledWith('e', 'cl', ['q1'], undefined);
    expect(alertas.motivoBloqueoCobro).not.toHaveBeenCalled();
    expect(cobros.createFromDistribucion).not.toHaveBeenCalled();
  });
  it('cobro simple: misma verificación con las cuotas imputadas', async () => {
    const { svc, cobros, alertas } = armar(null);
    cobros.verificarCuotasDelCliente.mockRejectedValue(new BadRequestException('no pertenecen'));
    await expect(svc.crear('e', 'u', simple)).rejects.toThrow(BadRequestException);
    expect(cobros.verificarCuotasDelCliente).toHaveBeenCalledWith('e', 'cl', ['q1']);
    expect(alertas.motivoBloqueoCobro).not.toHaveBeenCalled();
    expect(cobros.create).not.toHaveBeenCalled();
  });
});

describe('MobileCobrosService.mios · limit', () => {
  it('sin limit no pasa take (queda el corte por defecto)', async () => {
    const { svc, cobros } = armar(null);
    await svc.mios('e', 'u', '2026-10-27', '2026-11-02');
    expect(cobros.findAll.mock.calls[0][1].take).toBeUndefined();
  });
  it('con limit lo pasa, con tope', async () => {
    const { svc, cobros } = armar(null);
    await svc.mios('e', 'u', undefined, undefined, 200);
    expect(cobros.findAll.mock.calls[0][1].take).toBe(200);
    await svc.mios('e', 'u', undefined, undefined, 99999);
    expect(cobros.findAll.mock.calls[1][1].take).toBe(MIOS_LIMITE_MAXIMO);
  });
});

describe('AlertasClienteService.motivoBloqueoCobro', () => {
  type G = { id: string; estado_actual: string; fecha_ingreso: Date; observacion: string | null; deleted_at?: Date | null };
  // Prisma simulado: aplica el filtro de estado/borrado y el orden por fecha que pida el servicio.
  function conGestiones(gestiones: G[]) {
    const filtrar = ({ where, orderBy }: any) => {
      const r = gestiones.filter(
        (g) =>
          (where.deleted_at !== null || !g.deleted_at) &&
          (!where.estado_actual?.in || where.estado_actual.in.includes(g.estado_actual)),
      );
      if (orderBy?.fecha_ingreso === 'desc') r.sort((a, b) => +b.fecha_ingreso - +a.fecha_ingreso);
      return r;
    };
    const prisma: any = {
      cob_gestion_mora: {
        findMany: jest.fn(async (args: any) => filtrar(args)),
        findFirst: jest.fn(async (args: any) => filtrar(args)[0] ?? null),
      },
      cob_refinanciacion: { findFirst: jest.fn().mockResolvedValue(null) },
      promesas_pago: { count: jest.fn().mockResolvedValue(0) },
    };
    return new AlertasClienteService(prisma);
  }
  const g = (estado: string, dia: number, extra: Partial<G> = {}): G => ({
    id: `${estado}-${dia}`,
    estado_actual: estado,
    fecha_ingreso: new Date(2026, 0, dia),
    observacion: null,
    ...extra,
  });
  const conMora = (estado: string | null) => conGestiones(estado ? [g(estado, 1)] : []);

  it('INFORMCONF y DEMANDA devuelven motivo; gestión interna y nada, null', async () => {
    expect(await conMora('DEMANDA').motivoBloqueoCobro('e', 'c')).toContain('demanda judicial');
    expect(await conMora('INFORMCONF').motivoBloqueoCobro('e', 'c')).toContain('Informconf');
    expect(await conMora('GESTION_INTERNA').motivoBloqueoCobro('e', 'c')).toBeNull();
    expect(await conMora(null).motivoBloqueoCobro('e', 'c')).toBeNull();
  });
  it('el payload de alertas trae motivo_bloqueo', async () => {
    const r = await conMora('DEMANDA').getAlertas('e', 'c');
    expect(r.mora_avanzada?.motivo_bloqueo).toContain('Coordiná');
  });
  it('una gestión interna nueva no tapa una demanda vieja: bloquea y el banner muestra la demanda', async () => {
    const svc = conGestiones([g('DEMANDA', 1), g('GESTION_INTERNA', 20)]);
    expect(await svc.motivoBloqueoCobro('e', 'c')).toContain('demanda judicial');
    const r = await svc.getAlertas('e', 'c');
    expect(r.mora_avanzada?.estado).toBe('DEMANDA');
    expect(r.mora_avanzada?.bloquea_cobro).toBe(true);
  });
  it('la más grave gana: DEMANDA > INFORMCONF > gestión interna', async () => {
    const svc = conGestiones([g('INFORMCONF', 30), g('DEMANDA', 2), g('GESTION_INTERNA', 40)]);
    expect((await svc.getAlertas('e', 'c')).mora_avanzada?.estado).toBe('DEMANDA');
    expect(await svc.motivoBloqueoCobro('e', 'c')).toContain('demanda judicial');
  });
  it('una demanda borrada (deleted_at) no bloquea', async () => {
    const svc = conGestiones([g('DEMANDA', 1, { deleted_at: new Date() }), g('GESTION_INTERNA', 20)]);
    expect(await svc.motivoBloqueoCobro('e', 'c')).toBeNull();
    expect((await svc.getAlertas('e', 'c')).mora_avanzada?.estado).toBe('GESTION_INTERNA');
  });
});
