import { ViajeDocumentosService } from '../viaje-documentos.service';

describe('ViajeDocumentosService.detallar', () => {
  const crear = (overrides: any = {}) => {
    const prisma: any = {
      factura_cab: { findMany: jest.fn().mockResolvedValue([]) },
      nota_credito_cab: { findMany: jest.fn().mockResolvedValue([]) },
      nota_remision_cab: { findMany: jest.fn().mockResolvedValue([]) },
      recibos_cobro: { findMany: jest.fn().mockResolvedValue([]) },
      pedidos: { findMany: jest.fn().mockResolvedValue([]) },
      presupuesto_cab: { findMany: jest.fn().mockResolvedValue([]) },
      ...overrides,
    };
    const service = Object.create(ViajeDocumentosService.prototype) as any;
    service.prisma = prisma;
    return { service, prisma };
  };

  it('sin documentos devuelve lista vacía y no consulta ninguna tabla', async () => {
    const { service, prisma } = crear();
    expect(await service.detallar([])).toEqual([]);
    expect(prisma.factura_cab.findMany).not.toHaveBeenCalled();
  });

  it('resuelve el número, la fecha, el cliente y el total de una factura', async () => {
    const { service } = crear({
      factura_cab: {
        findMany: jest.fn().mockResolvedValue([
          {
            id: 'f-1', dest: '001', dpunexp: '001', dnumdoc: '0002371',
            dfeemide: new Date('2026-09-01'),
            moneda: { codigo: 'PYG' },
            clientes: { personas: { razon_social: 'GRUPO DULCE MARIA' } },
            factura_subtotales: [{ dtotgralope: 1_365_250 }],
          },
        ]),
      },
    });

    const r = await service.detallar([
      { id: 'vd-1', tipo: 'FACTURA', documento_id: 'f-1', agregado_auto: true, created_at: new Date() },
    ]);

    expect(r[0]).toEqual(
      expect.objectContaining({
        id: 'vd-1',
        tipo: 'FACTURA',
        documento_id: 'f-1',
        numero: '001-001-0002371',
        cliente: 'GRUPO DULCE MARIA',
        total: 1_365_250,
        moneda: 'PYG',
      }),
    );
  });

  it('un documento que ya no existe no rompe: queda sin número pero con la fila', async () => {
    const { service } = crear();
    const r = await service.detallar([
      { id: 'vd-9', tipo: 'FACTURA', documento_id: 'f-borrada', agregado_auto: false, created_at: new Date() },
    ]);
    expect(r).toHaveLength(1);
    expect(r[0]).toEqual(expect.objectContaining({ id: 'vd-9', numero: null, cliente: null }));
  });

  it('agrupa por tipo: una consulta por tabla, no una por documento', async () => {
    const { service, prisma } = crear({
      factura_cab: { findMany: jest.fn().mockResolvedValue([]) },
    });
    await service.detallar([
      { id: 'a', tipo: 'FACTURA', documento_id: 'f-1' },
      { id: 'b', tipo: 'FACTURA', documento_id: 'f-2' },
      { id: 'c', tipo: 'FACTURA', documento_id: 'f-3' },
    ]);
    expect(prisma.factura_cab.findMany).toHaveBeenCalledTimes(1);
    expect(prisma.factura_cab.findMany.mock.calls[0][0].where.id.in).toEqual(['f-1', 'f-2', 'f-3']);
  });

  it('resuelve el número de una orden de venta y de un recibo', async () => {
    const { service } = crear({
      pedidos: {
        findMany: jest.fn().mockResolvedValue([
          { id: 'p-1', numero_pedido: 'PED-0000002', fecha_pedido: new Date('2026-09-08'), total: 69_030,
            moneda: { codigo: 'PYG' }, cliente: { personas: { razon_social: 'AGROFERRETERIA' } } },
        ]),
      },
      recibos_cobro: {
        findMany: jest.fn().mockResolvedValue([
          { id: 'r-1', numero_recibo: 'REC-001', fecha_emision: new Date('2026-09-09'), monto_total: 50_000,
            moneda: { codigo: 'PYG' }, clientes: { personas: { razon_social: 'CASILLA BLAS' } } },
        ]),
      },
    });

    const r = await service.detallar([
      { id: 'vd-1', tipo: 'PEDIDO', documento_id: 'p-1' },
      { id: 'vd-2', tipo: 'RECIBO', documento_id: 'r-1' },
    ]);

    expect(r[0]).toEqual(expect.objectContaining({ numero: 'PED-0000002', cliente: 'AGROFERRETERIA', total: 69_030 }));
    expect(r[1]).toEqual(expect.objectContaining({ numero: 'REC-001', cliente: 'CASILLA BLAS', total: 50_000 }));
  });
});
