/** Tablero «lo mío»: en alcance propio la rentabilidad del dashboard cuenta solo las facturas del vendedor; los listados no cambian. */
import { ReportesRentabilidadService } from './reportes-rentabilidad.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 crear() {
  const prisma: any = {
    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_det: { findMany: jest.fn().mockResolvedValue([]) },
  };
  const svc = new ReportesRentabilidadService(prisma);
  jest.spyOn(svc as any, 'computeOverlayPorFactura').mockResolvedValue(new Map());
  return { prisma, svc };
}

const QUERY = { fecha_desde: '2026-11-01', fecha_hasta: '2026-11-07' };

async function dashboard(alcance: unknown, vista: 'tablero' | null = 'tablero') {
  alcanceMock.mockReset().mockResolvedValue(alcance);
  const { prisma, svc } = crear();
  await svc.getRentabilidadDashboard('emp', QUERY as any, 'usr', vista ?? undefined);
  return { prisma, svc, where: prisma.factura_det.findMany.mock.calls[0][0].where.factura_cab };
}

describe('getRentabilidadDashboard en alcance propio', () => {
  it('PROPIO vendedor: solo sus facturas', async () => {
    const { where } = await dashboard({ tipo: 'PROPIO', vendedorId: 'v1', cobradorId: null, nombre: 'Ana' });
    expect(alcanceMock).toHaveBeenCalledWith(expect.anything(), 'usr', 'emp');
    expect(where.AND).toContainEqual({ vendedor_id: 'v1' });
  });

  it('PROPIO sin vendedor: UUID_NULO', async () => {
    const { where } = await dashboard({ tipo: 'PROPIO', vendedorId: null, cobradorId: 'c1', nombre: 'Ana' });
    expect(where.AND).toContainEqual({ vendedor_id: UUID_NULO });
  });

  it('TODO: el where es el de siempre', async () => {
    const { where, svc } = await dashboard({ tipo: 'TODO' });
    expect(where).toEqual((svc as any).buildFacturaCabWhere('emp', QUERY, null));
    expect(JSON.stringify(where)).not.toContain('vendedor_id');
  });

  it('sin vista=tablero (Reporte de rentabilidad): ni consulta el alcance propio, el where es el de siempre', async () => {
    const { where, svc } = await dashboard({ tipo: 'PROPIO', vendedorId: 'v1', cobradorId: null, nombre: 'Ana', sinVinculo: false }, null);
    expect(alcanceMock).not.toHaveBeenCalled();
    expect(where).toEqual((svc as any).buildFacturaCabWhere('emp', QUERY, null));
  });

  it('vista=tablero sin vínculo: UUID_NULO', async () => {
    const { where } = await dashboard({ tipo: 'PROPIO', vendedorId: null, cobradorId: null, nombre: '', sinVinculo: true });
    expect(where.AND).toContainEqual({ vendedor_id: UUID_NULO });
  });

  it('los listados no consultan el alcance propio', async () => {
    alcanceMock.mockReset();
    const { prisma, svc } = crear();
    await svc.getRentabilidadProductos('emp', QUERY as any, 'usr');
    expect(alcanceMock).not.toHaveBeenCalled();
    expect(JSON.stringify(prisma.factura_det.findMany.mock.calls[0][0].where)).not.toContain('vendedor_id');
  });
});
