import { BadRequestException } from '@nestjs/common';
import { RecepcionesCompraService } from './recepciones-compra.service';
import { ComprasService } from 'src/compras/compras.service';
import { opcionesMatchingOc } from 'src/ordenes-compra/estado-oc';

jest.mock('src/stock/tipos-movimiento-inventario', () => ({
  tipoMovimientoInventarioId: jest.fn(async (_tx: unknown, codigo: string) => `tipo-${codigo}`),
}));
// Usuario sin restricción de sucursal: el alcance se prueba en recepciones-compra.service.spec.ts.
jest.mock('src/utils/alcance-sucursal', () => ({
  ...jest.requireActual('src/utils/alcance-sucursal'),
  alcanceSucursalUsuario: jest.fn().mockResolvedValue(null),
}));

/**
 * Matriz «Probar según configuración» del spec 2026-10-26-recepciones-compra.
 * La recepción corre de punta a punta contra una base en memoria (cabecera, líneas, movimientos, stock y lotes),
 * así se cuentan los movimientos reales. La factura posterior se mira con `resolveFlujoCompra` de `compras.service`,
 * montado como en `compras-oc-sin-recepcion.spec.ts`: devuelve si la factura mueve stock.
 *
 * Datos: OC `oc-1` con `det-1` (10 pedidas de `prod-1`, mercadería con lote) y `det-s` (1 de `serv-1`, un servicio).
 * Libre: `prov-1`, `dep-1`, `prod-1`.
 */

type Fila = {
  nombre: string;
  oc: boolean;
  /** `afectar_stock_en_compra_directa`: true = el stock entra con la factura (la recepción es constancia). */
  stockAlFacturar: boolean;
  matching: boolean;
};

const filas: Fila[] = [
  {
    nombre: 'OC encendida, stock al facturar, matching encendido (config real local)',
    oc: true,
    stockAlFacturar: true,
    matching: true,
  },
  { nombre: 'OC encendida, stock al facturar, matching apagado', oc: true, stockAlFacturar: true, matching: false },
  {
    nombre: 'OC encendida, stock al recepcionar, matching encendido',
    oc: true,
    stockAlFacturar: false,
    matching: true,
  },
  { nombre: 'OC encendida, stock al recepcionar, matching apagado', oc: true, stockAlFacturar: false, matching: false },
  { nombre: 'libre (OC apagada), stock al facturar', oc: false, stockAlFacturar: true, matching: false },
  { nombre: 'libre (OC apagada), stock al recepcionar', oc: false, stockAlFacturar: false, matching: false },
];

const configDe = (f: Fila) => ({
  empresa_id: 'emp-1',
  habilitar_orden_compra: f.oc,
  habilitar_recepcion_compra: true,
  habilitar_matching_3_vias: f.matching,
  afectar_stock_en_compra_directa: f.stockAlFacturar,
  modo_flujo_compra: 'directo',
});

/** Base en memoria con lo que tocan alta, edición y anulación de la recepción. */
const montarBase = (f: Fila) => {
  const db = {
    config: configDe(f) as Record<string, any>,
    cab: null as any,
    det: [] as any[],
    movimientos: [] as any[],
    stock: new Map<string, number>(),
    lotes: [] as any[],
    recibidoOc: new Map<string, number>([
      ['det-1', 0],
      ['det-s', 0],
    ]),
    productos: new Map<string, any>([
      ['prod-1', { id: 'prod-1', descripcion: 'Yogur', maneja_inventario: true, precio_costo: 50 }],
      ['serv-1', { id: 'serv-1', descripcion: 'Flete', maneja_inventario: false, precio_costo: 0 }],
    ]),
  };
  const clave = (dep: string, prod: string) => `${dep}|${prod}`;
  const lineasOc = () => [
    {
      id: 'det-1',
      producto_id: 'prod-1',
      cantidad: 10,
      cantidad_recibida: db.recibidoOc.get('det-1'),
      precio_unitario: 100,
    },
    {
      id: 'det-s',
      producto_id: 'serv-1',
      cantidad: 1,
      cantidad_recibida: db.recibidoOc.get('det-s'),
      precio_unitario: 30,
    },
  ];
  const conDetalle = () =>
    db.cab
      ? {
          ...db.cab,
          recepcion_compra_det: db.det.map((d) => ({ ...d })),
          orden_compra_cab: db.cab.orden_compra_id ? { id: 'oc-1', estado: 'pendiente', numero_orden: 'OC-1' } : null,
        }
      : null;
  let reloj = Date.parse('2026-10-05T13:00:00.000Z');

  const tx: any = {
    $executeRaw: jest.fn().mockResolvedValue(1),
    $queryRaw: jest.fn().mockResolvedValue([]),
    config_compras: { findUnique: jest.fn(async () => ({ ...db.config })), create: jest.fn() },
    orden_compra_cab: {
      findFirst: jest.fn(async () => ({
        id: 'oc-1',
        numero_orden: 'OC-1',
        sucursal_id: 'suc-1',
        proveedor_id: 'prov-1',
        estado: 'pendiente',
        orden_compra_det: lineasOc(),
      })),
    },
    orden_compra_det: {
      update: jest.fn(async ({ where, data }: any) => {
        const c = data.cantidad_recibida;
        const actual = db.recibidoOc.get(where.id) ?? 0;
        if (typeof c === 'number') db.recibidoOc.set(where.id, c);
        else if (c?.increment) db.recibidoOc.set(where.id, actual + c.increment);
        else if (c?.decrement) db.recibidoOc.set(where.id, actual - c.decrement);
      }),
      findMany: jest.fn(async ({ where }: any) => lineasOc().filter((l) => where.id.in.includes(l.id))),
    },
    compra_det: { findMany: jest.fn().mockResolvedValue([]) },
    proveedores: { findFirst: jest.fn().mockResolvedValue({ id: 'prov-1', tipo_entidad: 'PROVEEDOR_LOCAL' }) },
    depositos: { findFirst: jest.fn(async ({ where }: any) => ({ id: where.id ?? 'dep-1', sucursal_id: 'suc-1' })) },
    productos: {
      findMany: jest.fn(async ({ where }: any) =>
        where.id.in
          .map((id: string) => db.productos.get(id))
          .filter(Boolean)
          .map((p: any) => ({ ...p })),
      ),
    },
    recepcion_compra_cab: {
      create: jest.fn(async ({ data }: any) => {
        db.cab = { id: 'rec-1', ...data, updated_at: new Date(reloj) };
        return { ...db.cab };
      }),
      findFirst: jest.fn(async () => conDetalle()),
      update: jest.fn(async ({ data }: any) => {
        reloj += 60_000;
        db.cab = { ...db.cab, ...data, updated_at: new Date(reloj) };
      }),
    },
    recepcion_compra_det: {
      create: jest.fn(async ({ data }: any) => {
        const fila = { id: `rd-${db.det.length + 1}-${reloj}`, lote_id: null, ...data };
        db.det.push(fila);
        return { id: fila.id };
      }),
      update: jest.fn(async ({ where, data }: any) => {
        Object.assign(
          db.det.find((d) => d.id === where.id),
          data,
        );
      }),
      deleteMany: jest.fn(async () => {
        db.det = [];
      }),
    },
    stock_deposito: {
      upsert: jest.fn(async ({ where, update }: any) => {
        const { deposito_id, producto_id } = where.deposito_id_producto_id;
        const k = clave(deposito_id, producto_id);
        const delta = update.cantidad_disponible.increment ?? -update.cantidad_disponible.decrement;
        db.stock.set(k, (db.stock.get(k) ?? 0) + delta);
      }),
    },
    movimientos_inventario: {
      create: jest.fn(async ({ data }: any) => db.movimientos.push(data)),
      count: jest.fn(
        async ({ where }: any) =>
          db.movimientos.filter(
            (m) => m.documento_id === where.documento_id && m.documento_origen === where.documento_origen,
          ).length,
      ),
      findMany: jest.fn(async ({ where }: any) =>
        db.movimientos
          .filter(
            (m) => m.documento_id === where.documento_id && where.documento_origen.in.includes(m.documento_origen),
          )
          .map((m) => ({ ...m })),
      ),
    },
    lotes_producto: {
      findFirst: jest.fn().mockResolvedValue(null),
      update: jest.fn(async ({ where, data }: any) => {
        const l = db.lotes.find((x) => x.id === where.id);
        if (data.cantidad_inicial !== undefined) l.cantidad = data.cantidad_inicial;
        if (data.fecha_fabricacion !== undefined) l.fechaFabricacion = data.fecha_fabricacion;
        if (data.fecha_vencimiento !== undefined) l.fechaVencimiento = data.fecha_vencimiento;
        if (data.costo_unitario !== undefined) l.costoUnitario = data.costo_unitario;
        return { id: l.id };
      }),
      findUnique: jest.fn(async ({ where }: any) => {
        const l = db.lotes.find((x) => x.id === where.id);
        return l
          ? {
              numero_lote: l.numeroLote,
              fecha_fabricacion: l.fechaFabricacion ?? null,
              cantidad_inicial: l.cantidad,
              cantidad_disponible: l.disponible,
              productos: { descripcion: 'Yogur' },
              stock_lote: [{ cantidad_disponible: l.disponible }],
            }
          : null;
      }),
    },
    compra_costo_lote: { create: jest.fn(), findFirst: jest.fn().mockResolvedValue(null) },
  };
  const lotesService: any = {
    bloquearStockDe: jest.fn(),
    usaLotesEnDeposito: jest.fn().mockResolvedValue(true),
    generarNumeroLote: jest.fn(async () => `L20261005-00${db.lotes.length + 1}`),
    createLoteIngreso: jest.fn(async (_tx: unknown, p: any) => {
      const lote = { id: `lote-${db.lotes.length + 1}`, ...p, disponible: p.cantidad, activo: true };
      db.lotes.push(lote);
      return { id: lote.id };
    }),
    descontarDeLote: jest.fn(async (_tx: unknown, p: any) => {
      const l = db.lotes.find((x) => x.id === p.loteId);
      if (l) {
        l.disponible -= p.cantidad;
        l.activo = l.disponible > 0.0001;
      }
    }),
    ingresarEnLote: jest.fn(async (_tx: unknown, p: any) => {
      const l = db.lotes.find((x) => x.id === p.loteId);
      l.disponible += p.cantidad;
      l.activo = true;
    }),
  };
  const prisma = { $transaction: jest.fn(async (cb: any) => cb(tx)) };
  const ordenes = { recalculateOrdenCompraEstado: jest.fn().mockResolvedValue(undefined) };
  const audit = { log: jest.fn().mockResolvedValue(undefined) };
  const service = new RecepcionesCompraService(prisma as any, ordenes as any, audit as any, lotesService);
  jest.spyOn(service, 'findOne').mockImplementation(async () => conDetalle() as any);

  const de = (origen: string) => db.movimientos.filter((m) => m.documento_origen === origen);
  const stockDe = (prod = 'prod-1', dep = 'dep-1') => db.stock.get(clave(dep, prod)) ?? 0;
  /** Edita la recepción con el `updated_at` que tiene ahora (como el front al abrirla). */
  const editar = (dto: any) =>
    service.update('rec-1', { ...dto, updated_at: new Date(db.cab.updated_at).toISOString() } as any, 'emp-1', 'u-2');
  return {
    db,
    tx,
    service,
    lotesService,
    editar,
    stockDe,
    entradas: () => de('recepcion_compra'),
    reversas: () => de('recepcion_compra_reversa'),
  };
};

/** DTO de la recepción: con OC por línea (`det-1`, `det-s`) o libre por producto. */
const dtoDe = (f: Fila, cantidad = 4, extra: Record<string, unknown> = {}) =>
  (f.oc
    ? {
        cabecera: { orden_compra_id: 'oc-1', fecha_recepcion: '2026-10-05' },
        detalles: [{ orden_compra_det_id: 'det-1', cantidad_recibida: cantidad, ...extra }],
      }
    : {
        cabecera: { proveedor_id: 'prov-1', deposito_id: 'dep-1', fecha_recepcion: '2026-10-05' },
        detalles: [{ producto_id: 'prod-1', cantidad_recibida: cantidad, ...extra }],
      }) as any;

const ocDto = (detalles: any[]) =>
  ({ cabecera: { orden_compra_id: 'oc-1', fecha_recepcion: '2026-10-05' }, detalles }) as any;

/** ¿La factura posterior mueve stock? (`resolveFlujoCompra`, montado como en compras-oc-sin-recepcion.spec). */
const facturaMueveStock = async (f: Fila) => {
  const compras: any = new ComprasService({} as any, {} as any, {} as any, {} as any, {} as any, {} as any, { logEnTransaccion: jest.fn() } as any);
  const r = await compras.resolveFlujoCompra({
    tx: { orden_compra_det: { findMany: jest.fn().mockResolvedValue([]) } },
    empresaId: 'emp-1',
    configCompras: configDe(f),
    requisicionId: null,
    ordenCompraId: f.oc ? 'oc-1' : null,
    items: [
      {
        orden_compra_det_id: f.oc ? 'det-1' : null,
        requisicion_det_id: null,
        producto_id: 'prod-1',
        afecta_stock: true,
      },
    ],
  });
  return r.afectarStockEnCompra as boolean;
};

const codigoDe = (e: any) => e?.getResponse?.()?.codigo;

describe('Recepciones: matriz de configuración (spec «Probar según configuración»)', () => {
  describe.each(filas)('$nombre', (f) => {
    const mueve = !f.stockAlFacturar;

    it(`alta → ${mueve ? 'un movimiento y un lote en el depósito' : 'ningún movimiento ni lote (constancia)'}`, async () => {
      const { db, service, lotesService, entradas, stockDe } = montarBase(f);
      await service.create(dtoDe(f), 'emp-1', 'u-1');

      expect(entradas()).toHaveLength(mueve ? 1 : 0);
      expect(lotesService.createLoteIngreso).toHaveBeenCalledTimes(mueve ? 1 : 0);
      expect(stockDe()).toBe(mueve ? 4 : 0);
      if (mueve) expect(entradas()[0]).toMatchObject({ deposito_origen_id: 'dep-1', lote_id: 'lote-1', cantidad: 4 });
      // Con OC y constancia, la recepción queda sin depósito; la libre siempre guarda el elegido.
      expect(db.cab.deposito_id).toBe(f.oc && !mueve ? null : 'dep-1');
      if (f.oc) expect(db.recibidoOc.get('det-1')).toBe(4);
    });

    it('factura posterior → no duplica: el stock entra una sola vez', async () => {
      const { service, entradas } = montarBase(f);
      await service.create(dtoDe(f), 'emp-1', 'u-1');
      const factura = await facturaMueveStock(f);
      expect(factura).toBe(!mueve);
      expect(entradas().length + (factura ? 1 : 0)).toBe(1);
    });

    it(`anular → ${mueve ? 'revierte una vez' : 'no revierte (nunca movió)'}; una segunda anulación concurrente no revierte de nuevo`, async () => {
      const { db, tx, service, lotesService, reversas, stockDe } = montarBase(f);
      await service.create(dtoDe(f), 'emp-1', 'u-1');
      const antes = {
        ...db.cab,
        recepcion_compra_det: db.det.map((d) => ({ ...d })),
        orden_compra_cab: f.oc ? { id: 'oc-1', estado: 'pendiente', numero_orden: 'OC-1' } : null,
      };

      await service.anular('rec-1', { motivo: 'Error' } as any, 'emp-1', 'u-1');
      expect(reversas()).toHaveLength(mueve ? 1 : 0);
      expect(lotesService.descontarDeLote).toHaveBeenCalledTimes(mueve ? 1 : 0);
      expect(stockDe()).toBe(0);
      if (f.oc) expect(db.recibidoOc.get('det-1')).toBe(0);

      // La segunda leyó la recepción aplicada antes de esperar el lock rec:; la relectura ya la ve anulada.
      tx.recepcion_compra_cab.findFirst.mockResolvedValueOnce(antes);
      await expect(service.anular('rec-1', { motivo: 'Doble' } as any, 'emp-1', 'u-2')).rejects.toMatchObject({
        response: expect.objectContaining({ codigo: 'RECEPCION_ANULADA' }),
      });
      expect(reversas()).toHaveLength(mueve ? 1 : 0);
      expect(stockDe()).toBe(0);
      if (f.oc) expect(db.recibidoOc.get('det-1')).toBe(0);
    });

    it(`config cambiada después de recibir: editar sigue al documento (${mueve ? 'revierte y aplica, acepta lote' : 'constancia: no mueve, rechaza lote'})`, async () => {
      const { db, service, editar, entradas, reversas, stockDe, lotesService } = montarBase(f);
      await service.create(dtoDe(f), 'emp-1', 'u-1');
      db.config.afectar_stock_en_compra_directa = !db.config.afectar_stock_en_compra_directa;

      if (mueve) {
        await editar(dtoDe(f, 6, { numero_lote: 'A-9' }));
        expect(entradas()).toHaveLength(2);
        expect(reversas()).toHaveLength(1);
        expect(stockDe()).toBe(6);
        expect(lotesService.createLoteIngreso).toHaveBeenLastCalledWith(
          expect.anything(),
          expect.objectContaining({ numeroLote: 'A-9', cantidad: 6 }),
        );
      } else {
        await expect(editar(dtoDe(f, 6, { numero_lote: 'A-9' }))).rejects.toThrow(/se cargan en la factura/);
        await editar(dtoDe(f, 6));
        expect(entradas()).toHaveLength(0);
        expect(reversas()).toHaveLength(0);
        expect(stockDe()).toBe(0);
        expect(lotesService.createLoteIngreso).not.toHaveBeenCalled();
      }
      if (f.oc) expect(db.recibidoOc.get('det-1')).toBe(6);
    });

    if (mueve) {
      it('editar con lote consumido rechaza con LOTE_CONSUMIDO', async () => {
        const { db, service, editar } = montarBase(f);
        await service.create(dtoDe(f), 'emp-1', 'u-1');
        db.lotes[0].disponible = 1; // salieron 3 de las 4 unidades del lote
        const e = await editar(dtoDe(f, 6)).catch((err: unknown) => err);
        expect(codigoDe(e)).toBe('LOTE_CONSUMIDO');
        expect((e as any).message).toContain('ya salieron unidades');
      });
    }

    if (f.oc && f.stockAlFacturar && !f.matching) {
      it('el tope de lo pedido del 26/10 sigue: facturar 11 de 10 se rechaza', async () => {
        const compras: any = new ComprasService({} as any, {} as any, {} as any, {} as any, {} as any, {} as any, { logEnTransaccion: jest.fn() } as any);
        const tx = {
          orden_compra_cab: {
            findFirst: jest.fn().mockResolvedValue({
              id: 'oc-1',
              empresa_id: 'emp-1',
              proveedor_id: 'prov-1',
              estado: 'pendiente',
              orden_compra_det: [
                {
                  id: 'det-1',
                  producto_id: 'prod-1',
                  descripcion: 'Yogur',
                  cantidad: 10,
                  cantidad_recibida: 0,
                  precio_unitario: 100,
                },
              ],
            }),
          },
          compra_det: { findMany: jest.fn().mockResolvedValue([]) },
          config_compras: { findUnique: jest.fn().mockResolvedValue(configDe(f)), create: jest.fn() },
        };
        const item = (cantidad: number) => ({
          orden_compra_det_id: 'det-1',
          producto_id: 'prod-1',
          descripcion: 'Yogur',
          cantidad,
          precio_unitario: 100,
        });
        const validar = (cantidad: number) =>
          compras.validateMatchingOrdenCompra(
            tx,
            'emp-1',
            null,
            'prov-1',
            'oc-1',
            [item(cantidad)],
            opcionesMatchingOc(configDe(f)),
          );
        await expect(validar(10)).resolves.toBeUndefined();
        const e = await validar(11).catch((err: unknown) => err);
        expect(e).toBeInstanceOf(BadRequestException);
        expect((e as BadRequestException).message).toContain('supera lo pedido (10)');
      });
    }
  });

  describe('stock según el documento (OC, stock al recepcionar)', () => {
    const f = filas[2];

    it('OC con solo un servicio: queda con depósito y sin movimientos; editar sumando la mercadería aplica stock en su depósito y acepta lote', async () => {
      const { db, service, editar, entradas, stockDe, lotesService } = montarBase(f);
      await service.create(ocDto([{ orden_compra_det_id: 'det-s', cantidad_recibida: 1 }]), 'emp-1', 'u-1');
      expect(db.cab.deposito_id).toBe('dep-1');
      expect(entradas()).toHaveLength(0);

      await editar(
        ocDto([
          { orden_compra_det_id: 'det-s', cantidad_recibida: 1 },
          { orden_compra_det_id: 'det-1', cantidad_recibida: 4, numero_lote: 'A-1' },
        ]),
      );
      expect(stockDe('prod-1')).toBe(4);
      expect(stockDe('serv-1')).toBe(0);
      expect(entradas()).toHaveLength(1);
      expect(lotesService.createLoteIngreso).toHaveBeenCalledWith(
        expect.anything(),
        expect.objectContaining({ numeroLote: 'A-1', depositoId: 'dep-1' }),
      );
    });

    it('producto que pasó a manejar inventario después: anular no lo descuenta (nunca entró)', async () => {
      const { db, service, reversas, stockDe } = montarBase(f);
      await service.create(
        ocDto([
          { orden_compra_det_id: 'det-1', cantidad_recibida: 4 },
          { orden_compra_det_id: 'det-s', cantidad_recibida: 1 },
        ]),
        'emp-1',
        'u-1',
      );
      db.productos.get('serv-1').maneja_inventario = true;
      await service.anular('rec-1', {} as any, 'emp-1', 'u-1');
      expect(reversas().map((m) => m.producto_id)).toEqual(['prod-1']);
      expect(stockDe('prod-1')).toBe(0);
      expect(db.stock.has('dep-1|serv-1')).toBe(false);
    });

    it('producto que dejó de manejar inventario: anular sí descuenta lo que entró', async () => {
      const { db, service, reversas, stockDe } = montarBase(f);
      await service.create(ocDto([{ orden_compra_det_id: 'det-1', cantidad_recibida: 4 }]), 'emp-1', 'u-1');
      db.productos.get('prod-1').maneja_inventario = false;
      await service.anular('rec-1', {} as any, 'emp-1', 'u-1');
      expect(reversas()).toHaveLength(1);
      expect(reversas()[0]).toMatchObject({ producto_id: 'prod-1', cantidad: 4, lote_id: 'lote-1' });
      expect(stockDe('prod-1')).toBe(0);
    });

    it('editar dos veces seguidas no revierte de más', async () => {
      const { service, editar, reversas, stockDe, lotesService } = montarBase(f);
      await service.create(ocDto([{ orden_compra_det_id: 'det-1', cantidad_recibida: 4 }]), 'emp-1', 'u-1');
      await editar(ocDto([{ orden_compra_det_id: 'det-1', cantidad_recibida: 6 }]));
      await editar(ocDto([{ orden_compra_det_id: 'det-1', cantidad_recibida: 3 }]));
      expect(stockDe('prod-1')).toBe(3);
      expect(reversas().map((m) => [m.lote_id, m.cantidad])).toEqual([
        ['lote-1', 4],
        ['lote-2', 6],
      ]);
      expect(lotesService.descontarDeLote.mock.calls.map((c: any[]) => [c[1].loteId, c[1].cantidad])).toEqual([
        ['lote-1', 4],
        ['lote-2', 6],
      ]);
    });
  });

  describe('el lote sigue a la recepción al editar (ruling de la revisión final), con el servicio real', () => {
    const ocMueve = filas[2];
    const libreMueve = filas[5];

    describe.each([ocMueve, libreMueve])('$nombre', (f) => {
      it('entró con lote y hoy la sucursal no maneja lotes: editar conserva el lote y reingresa en la MISMA fila', async () => {
        const { db, editar, service, entradas, lotesService, stockDe } = montarBase(f);
        await service.create(dtoDe(f, 4, { numero_lote: 'A-1' }), 'emp-1', 'u-1');
        lotesService.usaLotesEnDeposito.mockResolvedValue(false);

        await editar(dtoDe(f, 6, { numero_lote: 'A-1', fecha_vencimiento: '2027-01-31' }));

        expect(lotesService.createLoteIngreso).toHaveBeenCalledTimes(1);
        expect(db.lotes).toHaveLength(1);
        expect(db.lotes[0]).toMatchObject({ id: 'lote-1', numeroLote: 'A-1', cantidad: 6, disponible: 6, activo: true });
        expect(db.lotes[0].fechaVencimiento).toEqual(new Date('2027-01-31T00:00:00.000Z'));
        expect(entradas().map((m) => [m.lote_id, m.cantidad])).toEqual([
          ['lote-1', 4],
          ['lote-1', 6],
        ]);
        expect(db.det[0]).toMatchObject({ lote_id: 'lote-1', numero_lote: 'A-1' });
        expect(stockDe()).toBe(6);
      });

      it('entró sin lote y hoy la sucursal maneja lotes: editar sigue sin lote', async () => {
        const { db, editar, service, entradas, lotesService, stockDe } = montarBase(f);
        lotesService.usaLotesEnDeposito.mockResolvedValue(false);
        await service.create(dtoDe(f, 4), 'emp-1', 'u-1');
        lotesService.usaLotesEnDeposito.mockResolvedValue(true);

        await editar(dtoDe(f, 6, { numero_lote: 'A-1' }));

        expect(lotesService.createLoteIngreso).not.toHaveBeenCalled();
        expect(entradas().map((m) => m.lote_id)).toEqual([null, null]);
        expect(db.det[0].lote_id).toBeNull();
        // y no graba el N° de lote que vino en el cuerpo (la línea sigue sin lote)
        expect(db.det[0].numero_lote ?? null).toBeNull();
        expect(stockDe()).toBe(6);
      });

      it('mismo número con lotes encendidos: no duplica la fila de lotes_producto', async () => {
        const { db, editar, service, lotesService } = montarBase(f);
        await service.create(dtoDe(f, 4, { numero_lote: 'A-1' }), 'emp-1', 'u-1');
        await editar(dtoDe(f, 6, { numero_lote: 'A-1' }));
        await editar(dtoDe(f, 3, { numero_lote: 'A-1' }));
        expect(lotesService.createLoteIngreso).toHaveBeenCalledTimes(1);
        expect(db.lotes).toHaveLength(1);
        expect(db.lotes[0]).toMatchObject({ cantidad: 3, disponible: 3 });
      });

      it('número cambiado: lote nuevo y el viejo queda revertido', async () => {
        const { db, editar, service, entradas } = montarBase(f);
        await service.create(dtoDe(f, 4, { numero_lote: 'A-1' }), 'emp-1', 'u-1');
        await editar(dtoDe(f, 6, { numero_lote: 'B-2' }));
        expect(db.lotes.map((l) => [l.numeroLote, l.disponible])).toEqual([
          ['A-1', 0],
          ['B-2', 6],
        ]);
        expect(entradas()[1].lote_id).toBe('lote-2');
      });
    });

    describe('libre que cambia de depósito', () => {
      const conLotesEn = (lotesService: any, deposito: string) =>
        lotesService.usaLotesEnDeposito.mockImplementation(async (_tx: unknown, _e: string, _p: string, dep: string) => dep === deposito);
      const aDep2 = (extra: Record<string, unknown> = {}) => {
        const dto = dtoDe(libreMueve, 4, extra);
        dto.cabecera.deposito_id = 'dep-2';
        return dto;
      };

      it('entró con lote en dep-1 y dep-2 no maneja lotes: conserva el lote (misma fila) y entra en dep-2', async () => {
        const { db, editar, service, entradas, lotesService, stockDe } = montarBase(libreMueve);
        conLotesEn(lotesService, 'dep-1');
        await service.create(dtoDe(libreMueve, 4, { numero_lote: 'A-1' }), 'emp-1', 'u-1');

        await editar(aDep2({ numero_lote: 'A-1' }));

        expect(db.cab.deposito_id).toBe('dep-2');
        expect(lotesService.createLoteIngreso).toHaveBeenCalledTimes(1);
        expect(entradas()[1]).toMatchObject({ deposito_origen_id: 'dep-2', lote_id: 'lote-1', cantidad: 4 });
        expect(lotesService.ingresarEnLote).toHaveBeenCalledWith(expect.anything(), { loteId: 'lote-1', depositoId: 'dep-2', cantidad: 4 });
        expect([stockDe('prod-1', 'dep-1'), stockDe('prod-1', 'dep-2')]).toEqual([0, 4]);
      });

      it('entró sin lote en dep-1 y dep-2 maneja lotes: sigue sin lote', async () => {
        const { db, editar, service, entradas, lotesService } = montarBase(libreMueve);
        conLotesEn(lotesService, 'dep-2');
        await service.create(dtoDe(libreMueve, 4), 'emp-1', 'u-1');

        await editar(aDep2({ numero_lote: 'A-1' }));

        expect(lotesService.createLoteIngreso).not.toHaveBeenCalled();
        expect(entradas()[1]).toMatchObject({ deposito_origen_id: 'dep-2', lote_id: null });
        expect(db.det[0].lote_id).toBeNull();
      });
    });
  });
});
