import { BadRequestException } from '@nestjs/common';
import { LotesService } from './lotes.service';

/** LT4: el stock previo pasa a un lote inicial; helpers de movimiento por lote. */
describe('LotesService - lote inicial y movimientos por lote', () => {
  const crearTx = (over: any = {}) => ({
    productos: { findFirst: jest.fn().mockResolvedValue({ id: 'p1', cod_producto: 'A-1', precio_costo: 700 }) },
    stock_deposito: {
      findMany: jest.fn().mockResolvedValue([
        { deposito_id: 'd1', cantidad_disponible: 10 },
        { deposito_id: 'd2', cantidad_disponible: 4 },
      ]),
    },
    stock_lote: {
      aggregate: jest.fn().mockResolvedValue({ _sum: { cantidad_disponible: 0 } }),
      upsert: jest.fn(),
      update: jest.fn(),
    },
    lotes_producto: {
      findFirst: jest.fn().mockResolvedValue(null),
      findUnique: jest.fn().mockResolvedValue({ numero_lote: 'L1' }),
      create: jest.fn().mockResolvedValue({ id: 'lote-ini' }),
      update: jest.fn().mockResolvedValue({ cantidad_disponible: 3 }),
    },
    $queryRaw: jest.fn().mockResolvedValue([{ deposito_id: 'd1', cantidad_disponible: 5 }]),
    ...over,
  });
  const service = new LotesService({} as any, {} as any);

  it('crea INICIAL-<código> sin vencimiento, con el costo del producto, y le pasa el stock de cada depósito', async () => {
    const tx: any = crearTx();
    const r = await service.crearLoteInicial(tx, { empresaId: 'emp', productoId: 'p1', usuarioId: 'u1' });
    expect(r).toEqual({ lote_id: 'lote-ini', cantidad: 14 });
    expect(tx.lotes_producto.create).toHaveBeenCalledWith(
      expect.objectContaining({
        data: expect.objectContaining({ numero_lote: 'INICIAL-A-1', fecha_vencimiento: null, costo_unitario: 700, cantidad_inicial: 14 }),
      }),
    );
    expect(tx.stock_lote.upsert).toHaveBeenCalledTimes(2);
  });

  it('solo asigna lo que todavía no está en un lote', async () => {
    const tx: any = crearTx();
    tx.stock_lote.aggregate.mockResolvedValueOnce({ _sum: { cantidad_disponible: 10 } }).mockResolvedValueOnce({ _sum: { cantidad_disponible: 1 } });
    const r = await service.crearLoteInicial(tx, { empresaId: 'emp', productoId: 'p1' });
    expect(r.cantidad).toBe(3);
  });

  it('sin stock no crea lote', async () => {
    const tx: any = crearTx({ stock_deposito: { findMany: jest.fn().mockResolvedValue([]) } });
    expect(await service.crearLoteInicial(tx, { empresaId: 'emp', productoId: 'p1' })).toEqual({ lote_id: null, cantidad: 0 });
    expect(tx.lotes_producto.create).not.toHaveBeenCalled();
  });

  it('descontarDeLote rechaza sacar más de lo que tiene el lote en el depósito', async () => {
    const tx: any = crearTx();
    await expect(service.descontarDeLote(tx, { loteId: 'l1', depositoId: 'd1', cantidad: 8 })).rejects.toBeInstanceOf(BadRequestException);
  });

  it('transferirLote pasa el stock del origen al destino', async () => {
    const tx: any = crearTx();
    await service.transferirLote(tx, { loteId: 'l1', origenId: 'd1', destinoId: 'd2', cantidad: 2 });
    expect(tx.stock_lote.update).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ cantidad_disponible: 3 }) }));
    expect(tx.stock_lote.upsert).toHaveBeenCalledWith(
      expect.objectContaining({ where: { lote_id_deposito_id: { lote_id: 'l1', deposito_id: 'd2' } } }),
    );
  });
});
