/** Tablero «lo mío» (con `vista=tablero`): en alcance propio el dashboard de ventas (y su período anterior) cuenta solo las facturas del vendedor. */
import { FacturasService } from './facturas.service';
import { resolverAlcancePropio, UUID_NULO } from 'src/utils/alcance-propio';

jest.mock('src/utils/alcance-sucursal', () => ({
  ...jest.requireActual('src/utils/alcance-sucursal'),
  alcanceSucursalUsuario: jest.fn().mockResolvedValue(null),
}));
jest.mock('src/utils/alcance-propio', () => ({
  ...jest.requireActual('src/utils/alcance-propio'),
  resolverAlcancePropio: jest.fn(),
}));
const alcanceMock = resolverAlcancePropio as jest.Mock;

function crearPrisma() {
  return {
    empresa_monedas: { findFirst: jest.fn().mockResolvedValue({ moneda_id: 'm-pyg' }) },
    moneda: {
      findFirst: jest.fn().mockResolvedValue({ id: 'm-pyg', codigo: 'PYG' }),
      findUnique: jest.fn().mockResolvedValue({ id: 'm-pyg', codigo: 'PYG' }),
      findMany: jest.fn().mockResolvedValue([]),
    },
    empresas_sucursales: { findMany: jest.fn().mockResolvedValue([]), findFirst: jest.fn().mockResolvedValue(null) },
    factura_cab: { findMany: jest.fn().mockResolvedValue([]) },
    factura_det: { aggregate: jest.fn().mockResolvedValue({ _sum: { dcantproser: 0 } }) },
  } as any;
}

const FILTROS = {
  fechaDesde: '2026-11-01',
  fechaHasta: '2026-11-07',
  fechaDesdeAnterior: '2026-10-01',
  fechaHastaAnterior: '2026-10-07',
  usuarioId: 'usr',
};

async function correr(alcance: unknown, vista: 'tablero' | null = 'tablero') {
  alcanceMock.mockReset().mockResolvedValue(alcance);
  const prisma = crearPrisma();
  const svc = new (FacturasService as any)(prisma);
  await svc.getDashboardVentas('emp', { ...FILTROS, vista: vista ?? undefined });
  const [actual, anterior] = prisma.factura_cab.findMany.mock.calls.map((c: any[]) => c[0].where);
  const anteriorAgg = prisma.factura_det.aggregate.mock.calls[0][0].where.factura_cab;
  return { svc, actual, anterior, anteriorAgg };
}

describe('getDashboardVentas en alcance propio', () => {
  it('PROPIO vendedor: actual, anterior y el agregado anterior filtran por su vendedor_id', async () => {
    const { actual, anterior, anteriorAgg } = await correr({ tipo: 'PROPIO', vendedorId: 'v1', cobradorId: null, nombre: 'Ana' });
    expect(alcanceMock).toHaveBeenCalledWith(expect.anything(), 'usr', 'emp');
    for (const w of [actual, anterior, anteriorAgg]) expect(w.AND).toContainEqual({ vendedor_id: 'v1' });
  });

  it('PROPIO sin vendedor (cobrador puro): UUID_NULO, nunca la empresa', async () => {
    const { actual, anterior } = await correr({ tipo: 'PROPIO', vendedorId: null, cobradorId: 'c1', nombre: 'Ana' });
    expect(actual.AND).toContainEqual({ vendedor_id: UUID_NULO });
    expect(anterior.AND).toContainEqual({ vendedor_id: UUID_NULO });
  });

  it('TODO: el where es el de siempre', async () => {
    const { svc, actual, anterior } = await correr({ tipo: 'TODO' });
    const esperado = (d: string, h: string) =>
      svc.buildWhereVentasValidas(svc.buildFacturasWhere('emp', { fechaDesde: d, fechaHasta: h }, null));
    expect(actual).toEqual(esperado(FILTROS.fechaDesde, FILTROS.fechaHasta));
    expect(anterior).toEqual(esperado(FILTROS.fechaDesdeAnterior, FILTROS.fechaHastaAnterior));
    expect(JSON.stringify(actual)).not.toContain('vendedor_id');
  });

  it('sin vista=tablero (pantallas viejas): ni consulta el alcance propio, el where es el de siempre', async () => {
    const { svc, actual } = await correr({ tipo: 'PROPIO', vendedorId: 'v1', cobradorId: null, nombre: 'Ana', sinVinculo: false }, null);
    expect(alcanceMock).not.toHaveBeenCalled();
    expect(actual).toEqual(svc.buildWhereVentasValidas(svc.buildFacturasWhere('emp', { fechaDesde: FILTROS.fechaDesde, fechaHasta: FILTROS.fechaHasta }, null)));
  });

  it('vista=tablero sin vínculo: UUID_NULO (vacío), nunca la empresa', async () => {
    const { actual, anterior } = await correr({ tipo: 'PROPIO', vendedorId: null, cobradorId: null, nombre: '', sinVinculo: true });
    expect(actual.AND).toContainEqual({ vendedor_id: UUID_NULO });
    expect(anterior.AND).toContainEqual({ vendedor_id: UUID_NULO });
  });
});
