import { LotesService } from './lotes.service';

function crearTx(filas: any[]) {
  return {
    $queryRaw: jest.fn().mockResolvedValue(filas),
    lotes_producto: {
      findFirst: jest.fn().mockResolvedValue(null),
      findUnique: jest.fn().mockResolvedValue({ numero_lote: 'L1' }),
      update: jest.fn().mockResolvedValue({ cantidad_disponible: 3 }),
    },
    stock_lote: { update: jest.fn(), upsert: jest.fn() },
  } as any;
}
const service = new LotesService({} as any, {} as any);
const transferencia = { loteId: 'l1', origenId: 'd1', destinoId: 'd2', cantidad: 2 };

describe('LotesService: códigos', () => {
  it('descontarDeLote por encima: LOTE_INSUFICIENTE con el texto de hoy', async () => {
    const tx = crearTx([{ cantidad_disponible: 5 }]);
    await expect(service.descontarDeLote(tx, { loteId: 'l1', depositoId: 'd1', cantidad: 8 })).rejects.toMatchObject({
      status: 400,
      message: 'El lote L1 tiene 5 en este depósito y se quieren sacar 8. Elegí otro lote o bajá la cantidad.',
      response: { codigo: 'LOTE_INSUFICIENTE', campo: 'cantidad', numero: 'L1', disponible: 5, pedido: 8 },
    });
    expect(tx.stock_lote.update).not.toHaveBeenCalled();
  });

  it('transferirLote por encima: LOTE_INSUFICIENTE con el texto de hoy', async () => {
    const tx = crearTx([{ deposito_id: 'd1', cantidad_disponible: 1 }]);
    await expect(service.transferirLote(tx, transferencia)).rejects.toMatchObject({
      status: 400,
      message: 'El lote L1 tiene 1 en el depósito de origen y se quieren transferir 2. Elegí otro lote o bajá la cantidad.',
      response: { codigo: 'LOTE_INSUFICIENTE', campo: 'cantidad', numero: 'L1', disponible: 1, pedido: 2 },
    });
  });

  it('loteDelProducto de otro producto: 404 LOTE_NO_ENCONTRADO con el texto de hoy', async () => {
    const tx = crearTx([]);
    await expect(service.loteDelProducto(tx, 'emp', 'p', 'l1')).rejects.toMatchObject({
      status: 404,
      message: 'El lote elegido no existe o es de otro producto. Volvé a elegir el lote de la lista.',
      response: { codigo: 'LOTE_NO_ENCONTRADO', campo: 'lote' },
    });
  });
});

describe('LotesService: tolerancia menor a la unidad mínima', () => {
  it('descontar 1,0001 de un lote con 1 se rechaza', async () => {
    const tx = crearTx([{ cantidad_disponible: 1 }]);
    await expect(service.descontarDeLote(tx, { loteId: 'l1', depositoId: 'd1', cantidad: 1.0001 })).rejects.toMatchObject({ response: { codigo: 'LOTE_INSUFICIENTE' } });
  });

  it('transferir 1,0001 de un lote con 1 se rechaza', async () => {
    const tx = crearTx([{ deposito_id: 'd1', cantidad_disponible: 1 }]);
    await expect(service.transferirLote(tx, { ...transferencia, cantidad: 1.0001 })).rejects.toMatchObject({ response: { codigo: 'LOTE_INSUFICIENTE' } });
  });

  it('descontar exactamente lo que hay pasa y deja cero', async () => {
    const tx = crearTx([{ cantidad_disponible: 1.0001 }]);
    await service.descontarDeLote(tx, { loteId: 'l1', depositoId: 'd1', cantidad: 1.0001 });
    expect(tx.stock_lote.update.mock.calls[0][0].data).toMatchObject({ cantidad_disponible: 0, active: false });
  });
});

describe('LotesService: bloqueos en orden', () => {
  it('transferirLote bloquea los dos depósitos en una consulta, en orden', async () => {
    const tx = crearTx([{ deposito_id: 'd1', cantidad_disponible: 5 }]);
    await service.transferirLote(tx, transferencia);
    const sql = tx.$queryRaw.mock.calls[0][0].join('');
    expect(sql).toContain('ORDER BY deposito_id');
    expect(sql).toContain('FOR UPDATE');
    expect(tx.$queryRaw.mock.calls[0].slice(1)).toEqual(['l1', 'd1', 'd2']);
  });

  it('toma el disponible del origen aunque el destino venga primero', async () => {
    const tx = crearTx([
      { deposito_id: 'd2', cantidad_disponible: 1 },
      { deposito_id: 'd1', cantidad_disponible: 5 },
    ]);
    await service.transferirLote(tx, transferencia);
    expect(tx.stock_lote.update.mock.calls[0][0].data.cantidad_disponible).toBe(3);
  });

  it('sin fila de origen no hay disponible, aunque el destino tenga', async () => {
    const tx = crearTx([{ deposito_id: 'd2', cantidad_disponible: 100 }]);
    await expect(service.transferirLote(tx, transferencia)).rejects.toMatchObject({ response: { codigo: 'LOTE_INSUFICIENTE', disponible: 0 } });
  });

  it('resta en origen y suma en destino, igual que antes', async () => {
    const tx = crearTx([{ deposito_id: 'd1', cantidad_disponible: 5 }]);
    await service.transferirLote(tx, transferencia);
    expect(tx.stock_lote.update).toHaveBeenCalledWith({
      where: { lote_id_deposito_id: { lote_id: 'l1', deposito_id: 'd1' } },
      data: expect.objectContaining({ cantidad_disponible: 3, active: true }),
    });
    expect(tx.stock_lote.upsert).toHaveBeenCalledWith(
      expect.objectContaining({
        where: { lote_id_deposito_id: { lote_id: 'l1', deposito_id: 'd2' } },
        create: { lote_id: 'l1', deposito_id: 'd2', cantidad_disponible: 2, active: true },
        update: expect.objectContaining({ cantidad_disponible: { increment: 2 } }),
      }),
    );
  });

  it('bloquearFilasLote: filas del lote atadas a empresa y producto, en orden, sin errores si no hay', async () => {
    const tx = crearTx([]);
    await expect(service.bloquearFilasLote(tx, { empresaId: 'emp', productoId: 'p', loteId: 'l1', depositoIds: ['d2', 'd1'] })).resolves.toBeUndefined();
    const [plantilla, ...valores] = tx.$queryRaw.mock.calls[0];
    const sql = plantilla.join('');
    expect(sql).toContain('ORDER BY sl.deposito_id');
    expect(sql).toContain('FOR UPDATE OF sl');
    expect(sql).toContain('lp.empresa_id');
    expect(sql).toContain('lp.producto_id');
    expect(valores.slice(0, 3)).toEqual(['l1', 'emp', 'p']);
    expect(valores[3].values).toEqual(['d2', 'd1']);
  });
  it('bloquearStockDe: lotes antes que stock_deposito, cada uno en el orden del cierre de inventario, por empresa y sin repetidos', async () => {
    const tx = crearTx([]);
    const pares = [
      { productoId: 'p2', depositoId: 'd1' },
      { productoId: 'p1', depositoId: 'd1' },
      { productoId: 'p2', depositoId: 'd1' },
    ];
    await expect(service.bloquearStockDe(tx, 'emp', pares)).resolves.toBeUndefined();
    expect(tx.$queryRaw).toHaveBeenCalledTimes(2);
    const [lotes, stock] = tx.$queryRaw.mock.calls.map(([plantilla, ...valores]: any[]) => ({ sql: plantilla.join(''), valores }));
    expect(lotes.sql).toContain('FROM stock_lote sl');
    expect(lotes.sql).toContain('lp.empresa_id');
    expect(lotes.sql).toContain('ORDER BY sl.deposito_id, sl.lote_id');
    expect(lotes.sql).toContain('FOR UPDATE OF sl');
    expect(stock.sql).toContain('FROM stock_deposito sd');
    expect(stock.sql).toContain('d.empresa_id');
    expect(stock.sql).toContain('ORDER BY sd.deposito_id, sd.producto_id');
    expect(stock.sql).toContain('FOR UPDATE OF sd');
    expect(lotes.valores[0]).toBe('emp');
    // Dos pares distintos: el repetido no se pide dos veces.
    expect(lotes.valores[1].values).toEqual(['p2', 'd1', 'p1', 'd1']);
  });

  it('bloquearStockDe: sin pares no consulta', async () => {
    const tx = crearTx([]);
    await service.bloquearStockDe(tx, 'emp', []);
    expect(tx.$queryRaw).not.toHaveBeenCalled();
  });
});
