import { sesionDeLaVenta } from './sesion-de-venta';

describe('sesionDeLaVenta', () => {
  const tx = (abiertas: { id: string; user_id: string | null }[]) => {
    const findMany = jest.fn().mockResolvedValue(abiertas);
    return { tx: { sesiones_caja: { findMany } } as any, findMany };
  };

  it('la contado usa la sesión de sus pagos sin consultar', async () => {
    const { tx: t, findMany } = tx([]);
    expect(await sesionDeLaVenta(t, { sesionesDePago: [null, 's-pago'], cajaDelPunto: 'c1', empresaId: 'e', usuarioId: 'u' })).toBe('s-pago');
    expect(findMany).not.toHaveBeenCalled();
  });

  it('la de crédito toma la sesión abierta de la caja del punto', async () => {
    const { tx: t, findMany } = tx([{ id: 's1', user_id: 'otro' }]);
    expect(await sesionDeLaVenta(t, { sesionesDePago: [], cajaDelPunto: 'c1', empresaId: 'e', usuarioId: 'u' })).toBe('s1');
    expect(findMany.mock.calls[0][0].where).toEqual({ empresa_id: 'e', estado: 'ABIERTA', caja_id: 'c1' });
  });

  it('con varias abiertas en la caja elige la del vendedor; si ninguna es suya, null (no adivina)', async () => {
    expect(await sesionDeLaVenta(tx([{ id: 'a', user_id: 'x' }, { id: 'b', user_id: 'u' }]).tx, { sesionesDePago: [], cajaDelPunto: 'c1', empresaId: 'e', usuarioId: 'u' })).toBe('b');
    expect(await sesionDeLaVenta(tx([{ id: 'a', user_id: 'x' }, { id: 'b', user_id: 'y' }]).tx, { sesionesDePago: [], cajaDelPunto: 'c1', empresaId: 'e', usuarioId: 'u' })).toBeNull();
  });

  it('punto sin caja: la sesión abierta del vendedor; sin vendedor, null', async () => {
    const { tx: t, findMany } = tx([{ id: 's-propia', user_id: 'u' }]);
    expect(await sesionDeLaVenta(t, { sesionesDePago: [], cajaDelPunto: null, empresaId: 'e', usuarioId: 'u' })).toBe('s-propia');
    expect(findMany.mock.calls[0][0].where).toEqual({ empresa_id: 'e', estado: 'ABIERTA', user_id: 'u' });
    expect(await sesionDeLaVenta(tx([]).tx, { sesionesDePago: [], cajaDelPunto: null, empresaId: 'e', usuarioId: undefined })).toBeNull();
  });

  it('sin sesión abierta queda en null', async () => {
    expect(await sesionDeLaVenta(tx([]).tx, { sesionesDePago: [], cajaDelPunto: 'c1', empresaId: 'e', usuarioId: 'u' })).toBeNull();
  });
});
