import { BadRequestException } from '@nestjs/common';
import { StockService } from './stock.service';

jest.mock('src/utils/alcance-sucursal', () => ({ alcanceSucursalUsuario: jest.fn().mockResolvedValue(null), filtroSucursalDeposito: jest.fn() }));
jest.mock('src/productos/permisos-columnas', () => ({ resolverPermisos: jest.fn().mockResolvedValue(new Set(['INV_STK_COSTO_VER'])) }));

/**
 * Ajuste, transferencia y carga desde la ficha:
 *  - S9: una salida no puede dejar menos que lo reservado.
 *  - LT6: con lotes, el ajuste y la transferencia mueven el stock del lote.
 *  - S17: POST /stock graba la diferencia como ajuste (antes pisaba sin movimiento).
 */
describe('StockService - ajuste/transferencia con lotes y reservas', () => {
  const crear = (opts: { actual?: number; reservado?: number; usaLotes?: boolean; sinLote?: number } = {}) => {
    const tx: any = {
      $queryRaw: jest.fn().mockResolvedValue([
        { deposito_id: 'dep-1', cantidad_disponible: opts.actual ?? 10, cantidad_reservada: opts.reservado ?? 0 },
      ]),
      tipo_movimiento_inventario: {
        findUnique: jest.fn().mockResolvedValue({ id: 'tipo-1' }),
        upsert: jest.fn(),
      },
      stock_deposito: {
        upsert: jest.fn().mockResolvedValue({ id: 'sd-1', producto: {}, deposito: {} }),
        update: jest.fn().mockResolvedValue({}),
      },
      movimientos_inventario: { create: jest.fn().mockResolvedValue({ id: 'mov-1' }) },
      lotes_producto: { findFirst: jest.fn().mockResolvedValue(null) },
      productos: { findUnique: jest.fn().mockResolvedValue({ precio_costo: 700 }) },
    };
    const prisma: any = {
      $transaction: jest.fn(async (cb: any) => cb(tx)),
      depositos: { count: jest.fn(async (a: any) => new Set(a.where.id.in).size), findMany: jest.fn().mockResolvedValue([]) },
      productos: { findFirst: jest.fn().mockResolvedValue({ maneja_inventario: true }), findUnique: jest.fn().mockResolvedValue(null) },
      stock_deposito: { findUnique: jest.fn().mockResolvedValue(null) },
    };
    const lotes: any = {
      usaLotesEnDeposito: jest.fn().mockResolvedValue(!!opts.usaLotes),
      loteDelProducto: jest.fn().mockResolvedValue({ id: 'lote-1' }),
      descontarDeLote: jest.fn(),
      ingresarEnLote: jest.fn(),
      transferirLote: jest.fn(),
      bloquearFilasLote: jest.fn(),
      createLoteIngreso: jest.fn().mockResolvedValue({ id: 'lote-nuevo' }),
    };
    const fifo: any = { cantidadSinLote: jest.fn().mockResolvedValue(opts.sinLote ?? 0) };
    const audit: any = { log: jest.fn() };
    const service = new StockService(prisma, audit, lotes, fifo);
    return { service, tx, prisma, lotes, fifo };
  };

  const ajuste = (cantidad: number, extra: any = {}) => ({ deposito_id: 'dep-1', producto_id: 'prod-1', cantidad, ...extra });

  it('S9: rechaza la salida que deja menos que lo reservado', async () => {
    const { service, tx } = crear({ actual: 10, reservado: 8 });
    await expect(service.ajustarStock(ajuste(-5), 'u1', 'AJUSTE_NEGATIVO', 'emp')).rejects.toThrow(/reservado/);
    expect(tx.movimientos_inventario.create).not.toHaveBeenCalled();
  });

  it('S9: deja sacar hasta lo libre', async () => {
    const { service, tx } = crear({ actual: 10, reservado: 8 });
    await service.ajustarStock(ajuste(-2), 'u1', 'AJUSTE_NEGATIVO', 'emp');
    expect(tx.stock_deposito.upsert).toHaveBeenCalledWith(expect.objectContaining({ update: expect.objectContaining({ cantidad_disponible: 8 }) }));
  });

  it('LT6: la salida con lote descuenta del lote y el movimiento lleva el lote', async () => {
    const { service, tx, lotes } = crear({ usaLotes: true });
    await service.ajustarStock(ajuste(-3, { lote_id: 'lote-1' }), 'u1', 'AJUSTE_NEGATIVO', 'emp');
    expect(lotes.descontarDeLote).toHaveBeenCalledWith(tx, { loteId: 'lote-1', depositoId: 'dep-1', cantidad: 3 });
    expect(tx.movimientos_inventario.create).toHaveBeenCalledWith({ data: expect.objectContaining({ lote_id: 'lote-1' }) });
  });

  it('LT6: la salida sin lote de un producto con lotes no puede superar el stock sin lote', async () => {
    const { service } = crear({ usaLotes: true, sinLote: 1 });
    await expect(service.ajustarStock(ajuste(-3), 'u1', 'AJUSTE_NEGATIVO', 'emp')).rejects.toThrow(/elegí de qué lote sale/);
  });

  it('LT6: la entrada de un producto con lotes exige lote', async () => {
    const { service } = crear({ usaLotes: true });
    await expect(service.ajustarStock(ajuste(4), 'u1', 'AJUSTE_POSITIVO', 'emp')).rejects.toBeInstanceOf(BadRequestException);
  });

  it('LT6: la entrada a un lote nuevo lo crea con el costo del producto', async () => {
    const { service, lotes, tx } = crear({ usaLotes: true });
    await service.ajustarStock(
      ajuste(4, { nuevo_lote: { numero_lote: 'L-1', fecha_vencimiento: '2027-01-31' } }),
      'u1',
      'AJUSTE_POSITIVO',
      'emp',
    );
    expect(lotes.createLoteIngreso).toHaveBeenCalledWith(
      tx,
      expect.objectContaining({ numeroLote: 'L-1', cantidad: 4, costoUnitario: 700, fechaVencimiento: new Date('2027-01-31T00:00:00.000Z') }),
    );
    expect(tx.movimientos_inventario.create).toHaveBeenCalledWith({ data: expect.objectContaining({ lote_id: 'lote-nuevo' }) });
  });

  it('rechaza lote en un producto que no se controla por lote', async () => {
    const { service } = crear({ usaLotes: false });
    await expect(service.ajustarStock(ajuste(-1, { lote_id: 'lote-1' }), 'u1', 'AJUSTE_NEGATIVO', 'emp')).rejects.toThrow(/no se controla por lote/);
  });

  it('LT6: la transferencia mueve el lote al destino', async () => {
    const { service, lotes, tx } = crear({ usaLotes: true });
    await service.transferirStock(
      { deposito_origen_id: 'dep-1', deposito_destino_id: 'dep-2', producto_id: 'prod-1', cantidad: 2, lote_id: 'lote-1' },
      'u1',
      'emp',
    );
    expect(lotes.transferirLote).toHaveBeenCalledWith(tx, { loteId: 'lote-1', origenId: 'dep-1', destinoId: 'dep-2', cantidad: 2 });
    expect(tx.movimientos_inventario.create).toHaveBeenCalledWith({ data: expect.objectContaining({ lote_id: 'lote-1', deposito_destino_id: 'dep-2' }) });
  });

  it('S17: POST /stock graba la diferencia como ajuste', async () => {
    const { service, tx } = crear({ actual: 10 });
    await service.upsertStock({ deposito_id: 'dep-1', producto_id: 'prod-1', cantidad_disponible: 14 }, 'u1', 'emp');
    expect(tx.movimientos_inventario.create).toHaveBeenCalledWith({
      data: expect.objectContaining({ cantidad: 4, documento_origen: 'ajuste_manual', tipo_movimiento_id: 'tipo-1' }),
    });
  });

  it('S17: sin diferencia no graba movimiento', async () => {
    const { service, tx } = crear({ actual: 10 });
    await service.upsertStock({ deposito_id: 'dep-1', producto_id: 'prod-1', cantidad_disponible: 10, stock_minimo: 2 }, 'u1', 'emp');
    expect(tx.movimientos_inventario.create).not.toHaveBeenCalled();
  });
});
