import { ValidationPipe } from '@nestjs/common';
import { REQUIRE_PERMISSION_KEY } from 'src/auth/decorators/require-permission.decorator';
import { REQUIRE_SUBMODULO_KEY } from 'src/auth/decorators/require-submodulo.decorator';
import { LotesService } from 'src/lotes/lotes.service';
import { alcanceSucursalUsuario } from 'src/utils/alcance-sucursal';
import { LiberarEmbarqueDto } from './dto/importaciones.dto';
import { ImportacionesController } from './importaciones.controller';
import { ImportacionesService } from './services/importaciones.service';

jest.mock('src/stock/tipos-movimiento-inventario', () => ({ tipoMovimientoInventarioId: jest.fn(async (_tx: unknown, codigo: string) => `tipo-${codigo}`) }));
jest.mock('src/utils/alcance-sucursal', () => ({ alcanceSucursalUsuario: jest.fn(async () => null) }));

/**
 * Liberar al depósito con lock, vista previa, alcance de depósitos y sin saltear ítems (plan Task 13; spec B1, B3, B16,
 * filas 4, 20, 21 y 22 de la matriz; preflight F15, F25).
 *
 * Un «mundo» con estado: el Prisma de mentira guarda stock, movimientos, ítems, lotes y bitácora. `$executeRaw` (el
 * `pg_advisory_xact_lock` de `imp:`) es un mutex real que se suelta al terminar la transacción, así dos liberaciones a la
 * vez se serializan como en Postgres. `LotesService` es el real salvo `isEnabledForEmpresa` (sucursales con lotes) y
 * `createLoteIngreso`.
 */

const EMPRESA = 'emp';
const alcance = alcanceSucursalUsuario as jest.MockedFunction<typeof alcanceSucursalUsuario>;

type Fila = Record<string, any>;

interface Opciones {
  perfil?: 'AUTOS' | 'CONSUMO_MASIVO';
  estado?: string;
  items?: Fila[];
  productos?: Fila[];
  contabilidad?: boolean;
  despacho?: Fila | null;
  sucursalesConLotes?: string[];
  lotes?: Fila[];
}

const producto = (id: string, extra: Fila = {}) => ({
  id,
  empresa_id: EMPRESA,
  cod_producto: `COD-${id}`,
  descripcion: `Producto ${id}`,
  maneja_inventario: true,
  maneja_lote: false,
  deleted: false,
  ...extra,
});

const itemCm = (id: string, productoId: string | null, extra: Fila = {}) => ({
  id,
  empresa_id: EMPRESA,
  embarque_id: 'emb-1',
  activo: true,
  producto_id: productoId,
  sku_interno_id: null,
  chasis: null,
  marca: null,
  modelo: null,
  anio: null,
  cantidad: 10,
  costo_unitario_gs: 1500,
  estado: 'PENDIENTE',
  lote_id: null,
  ...extra,
});

function mundo(o: Opciones = {}) {
  const st = {
    embarque: { id: 'emb-1', empresa_id: EMPRESA, numero: 'IMP-2026-000009', estado: o.estado ?? 'DESPACHADO', perfil: o.perfil ?? 'CONSUMO_MASIVO', activo: true } as Fila,
    despacho: (o.despacho === undefined
      ? { id: 'des-1', empresa_id: EMPRESA, embarque_id: 'emb-1', estado: 'CONFIRMADO', asiento_estado: 'GENERADO', asiento_codigo: null }
      : o.despacho) as Fila | null,
    items: (o.items ?? [itemCm('it-1', 'p1'), itemCm('it-2', 'p2', { cantidad: 4, costo_unitario_gs: 800.5 })]).map((i, n) => ({ orden: n + 1, ...i })),
    productos: o.productos ?? [producto('p1'), producto('p2')],
    depositos: [
      { id: 'dep-1', empresa_id: EMPRESA, descripcion: 'Central', sucursal_id: 'suc-1', active: true },
      { id: 'dep-2', empresa_id: EMPRESA, descripcion: 'Encarnación', sucursal_id: 'suc-2', active: true },
      { id: 'dep-3', empresa_id: EMPRESA, descripcion: 'Tránsito', sucursal_id: null, active: true },
    ],
    stock: new Map<string, { cantidad_disponible: number; cantidad_reservada: number }>(),
    movimientos: [] as Fila[],
    bitacora: [] as Fila[],
    lotes: (o.lotes ?? []) as Fila[],
    productosCreados: [] as Fila[],
  };
  const conProducto = (p: Fila | undefined) => (p ? { ...p } : null);
  const coincide = (fila: Fila, where: Fila = {}) =>
    Object.entries(where).every(([k, v]) => {
      if (v && typeof v === 'object' && 'in' in v) return (v.in as unknown[]).includes(fila[k]);
      if (v && typeof v === 'object') return true;
      return fila[k] === v;
    });

  const crearTx = (bloquear: () => Promise<void>) => {
    const tx: any = {
      $executeRaw: jest.fn(async () => bloquear()),
      // bloquearStockDe (SELECT … FOR UPDATE): en el mundo de mentira no hay otra transacción que esperar.
      $queryRaw: jest.fn(async () => []),
      imp_config_empresa: { findUnique: jest.fn(async () => ({ empresa_id: EMPRESA, modulo_operativo_activo: true, perfil_activo: st.embarque.perfil })) },
      imp_embarques: {
        findFirst: jest.fn(async ({ where }: any) => (coincide(st.embarque, where) ? { ...st.embarque } : null)),
        update: jest.fn(async ({ data }: any) => Object.assign(st.embarque, data)),
      },
      imp_despachos: { findFirst: jest.fn(async () => (st.despacho ? { ...st.despacho } : null)) },
      // El documento del despacho: el mundo es coherente, GENERADO tiene su documento CONFIRMADO (estado vigente, F5).
      cont_documentos: {
        findFirst: jest.fn(() => Promise.resolve(st.despacho?.asiento_estado === 'GENERADO' ? { id: 'doc-des', asiento: { numero: 1 } } : null)),
      },
      depositos: { findFirst: jest.fn(async ({ where }: any) => conProducto(st.depositos.find((d) => coincide(d, where)))) },
      imp_embarque_items: {
        findMany: jest.fn(async ({ where }: any) => st.items.filter((i) => coincide(i, where)).map((i) => ({ ...i }))),
        update: jest.fn(async ({ where, data }: any) => Object.assign(st.items.find((i) => i.id === where.id) as Fila, data)),
        updateMany: jest.fn(async ({ where, data }: any) => {
          const filas = st.items.filter((i) => coincide(i, where));
          filas.forEach((i) => Object.assign(i, data));
          return { count: filas.length };
        }),
      },
      productos: {
        findMany: jest.fn(async ({ where }: any) => st.productos.filter((p) => coincide(p, where)).map((p) => ({ ...p }))),
        findFirst: jest.fn(async ({ where }: any) => conProducto(st.productos.find((p) => coincide(p, where)))),
        create: jest.fn(async ({ data }: any) => {
          const nuevo = { id: `nuevo-${st.productosCreados.length + 1}`, ...data };
          st.productos.push(nuevo);
          st.productosCreados.push(nuevo);
          return nuevo;
        }),
      },
      unidades_de_medida: { findFirst: jest.fn(async () => ({ id: 'um-uni' })) },
      afectacion_iva: { findFirst: jest.fn(async () => ({ id: 'af-10' })) },
      stock_deposito: {
        upsert: jest.fn(async ({ where, update, create }: any) => {
          const clave = `${where.deposito_id_producto_id.deposito_id}|${where.deposito_id_producto_id.producto_id}`;
          const actual = st.stock.get(clave);
          if (actual) actual.cantidad_disponible += Number(update.cantidad_disponible.increment);
          else st.stock.set(clave, { cantidad_disponible: Number(create.cantidad_disponible), cantidad_reservada: 0 });
        }),
        findUnique: jest.fn(async ({ where }: any) => {
          const k = where.deposito_id_producto_id;
          return st.stock.get(`${k.deposito_id}|${k.producto_id}`) ?? null;
        }),
        update: jest.fn(async ({ where, data }: any) => {
          const k = where.deposito_id_producto_id;
          const actual = st.stock.get(`${k.deposito_id}|${k.producto_id}`) as { cantidad_disponible: number };
          actual.cantidad_disponible -= Number(data.cantidad_disponible.decrement);
        }),
      },
      movimientos_inventario: {
        create: jest.fn(async ({ data }: any) => st.movimientos.push({ created_at: new Date(), ...data })),
        findMany: jest.fn(async ({ where }: any) => {
          if (where.documento_id) {
            return st.movimientos
              .filter((m) => m.documento_id === where.documento_id && where.documento_origen.in.includes(m.documento_origen))
              .map((m) => {
                const p = st.productos.find((x) => x.id === m.producto_id);
                const lote = st.lotes.find((l) => l.id === m.lote_id);
                return {
                  ...m,
                  producto: { id: p?.id, cod_producto: p?.cod_producto, descripcion: p?.descripcion },
                  lote: lote ? { id: lote.id, numero_lote: lote.numero_lote } : null,
                };
              });
          }
          return st.movimientos.filter((m) => m.salida && m.created_at > where.created_at.gt);
        }),
      },
      tipo_movimiento_inventario: { findMany: jest.fn(async () => [{ id: 'tipo-VENTA' }]) },
      lotes_producto: {
        findFirst: jest.fn(async ({ where }: any) => {
          const l = st.lotes.find((x) => coincide(x, where));
          return l ? { id: l.id, productos: { descripcion: st.productos.find((p) => p.id === l.producto_id)?.descripcion } } : null;
        }),
        findMany: jest.fn(async () => []),
        findUnique: jest.fn(async ({ where }: any) => {
          const l = st.lotes.find((x) => x.id === where.id);
          return l ? { cantidad_disponible: l.cantidad_disponible } : null;
        }),
      },
      stock_lote: {
        findUnique: jest.fn(async ({ where }: any) => {
          const l = st.lotes.find((x) => x.id === where.lote_id_deposito_id.lote_id);
          return l ? { cantidad_disponible: l.en_deposito ?? l.cantidad_disponible } : null;
        }),
      },
      imp_embarques_bitacora: { create: jest.fn(async ({ data }: any) => st.bitacora.push(data)) },
    };
    return tx;
  };

  // `pg_advisory_xact_lock` de mentira: una sola clave (un embarque), se suelta al terminar la transacción.
  let cola: Promise<void> = Promise.resolve();
  const txs: any[] = [];
  const prisma: any = {
    $transaction: jest.fn(async (cb: (tx: any) => Promise<unknown>) => {
      let soltar: () => void = () => undefined;
      let tomado = false;
      const tx = crearTx(async () => {
        if (tomado) return;
        tomado = true;
        const previo = cola;
        cola = new Promise<void>((r) => (soltar = r));
        await previo;
      });
      txs.push(tx);
      try {
        return await cb(tx);
      } finally {
        soltar();
      }
    }),
  };

  const conLotes = new Set(o.sucursalesConLotes ?? []);
  let nLote = 0;
  const lotesService: any = Object.assign(Object.create(LotesService.prototype), {
    isEnabledForEmpresa: jest.fn(async (_e: string, sucursalId: string) => conLotes.has(sucursalId)),
    createLoteIngreso: jest.fn(async (_tx: unknown, p: Fila) => {
      const lote = { id: `lote-${++nLote}`, producto_id: p.productoId, numero_lote: p.numeroLote, cantidad_disponible: p.cantidad };
      st.lotes.push(lote);
      return lote;
    }),
    descontarDeLote: jest.fn(async () => undefined),
  });
  const contabilidad: any = { tieneModuloContabilidad: jest.fn(async () => o.contabilidad ?? false) };
  const fifo: any = { cantidadSinLote: jest.fn(async () => 0) };
  const service = new ImportacionesService(prisma, {} as any, {} as any, contabilidad, {} as any, lotesService, fifo);

  const liberar = (deposito = 'dep-1', lotes?: Fila[]) =>
    service.liberarEmbarque('emb-1', { deposito_destino_id: deposito, ...(lotes ? { lotes } : {}) } as LiberarEmbarqueDto, EMPRESA, 'u-1');
  const vista = (deposito?: string) => service.vistaLiberacion('emb-1', EMPRESA, 'u-1', deposito);
  const revertir = (motivo = 'Se liberó al depósito equivocado') => service.revertirLiberacion('emb-1', { motivo }, EMPRESA, 'u-1');
  const error = async (p: Promise<unknown>) => {
    try {
      await p;
    } catch (e: any) {
      return { status: e.getStatus?.(), ...(e.getResponse?.() ?? {}) };
    }
    throw new Error('se esperaba un error');
  };
  return { st, service, prisma, txs, lotesService, contabilidad, liberar, vista, revertir, error };
}

beforeEach(() => {
  alcance.mockReset();
  alcance.mockResolvedValue(null);
});

describe('liberar: lock y relectura (B3)', () => {
  it('dos liberaciones: la segunda relee bajo imp: y recibe ESTADO_CAMBIADO; el stock suma una vez', async () => {
    const m = mundo();
    const [a, b] = await Promise.allSettled([m.liberar(), m.liberar()]);

    expect(a.status).toBe('fulfilled');
    expect(b.status).toBe('rejected');
    const e = (b as PromiseRejectedResult).reason;
    expect(e.getStatus()).toBe(409);
    expect(e.getResponse()).toMatchObject({ codigo: 'ESTADO_CAMBIADO', estado_actual: 'LIBERADO', estado_pedido: 'LIBERADO' });

    expect(m.st.stock.get('dep-1|p1')?.cantidad_disponible).toBe(10);
    expect(m.st.stock.get('dep-1|p2')?.cantidad_disponible).toBe(4);
    expect(m.st.movimientos).toHaveLength(2);
    // el lock se toma antes de leer el embarque
    for (const tx of m.txs) {
      expect(tx.$executeRaw.mock.invocationCallOrder[0]).toBeLessThan(tx.imp_embarques.findFirst.mock.invocationCallOrder[0]);
    }
    expect(m.st.bitacora.filter((b) => b.evento === 'EMBARQUE_LIBERADO')).toHaveLength(1);
  });

  it('fuera de DESPACHADO → 409 ESTADO_CAMBIADO con el estado actual', async () => {
    const m = mundo({ estado: 'ARRIBADO' });
    expect(await m.error(m.liberar())).toMatchObject({ status: 409, codigo: 'ESTADO_CAMBIADO', estado_actual: 'ARRIBADO' });
  });
});

describe('liberar: errores de la vista con linea (B16, fila 4)', () => {
  const autos = (chasis: Array<string | null>) =>
    chasis.map((c, i) => itemCm(`it-${i + 1}`, null, { chasis: c, marca: 'Toyota', modelo: 'Hilux', cantidad: 1, costo_unitario_gs: 100_000_000 }));

  it('AUTOS con un ítem sin chasis → ITEM_SIN_CHASIS linea 2, sin escribir nada', async () => {
    const m = mundo({ perfil: 'AUTOS', items: autos(['8AJBA3CD1N1234567', null]), productos: [] });
    expect(await m.error(m.liberar())).toMatchObject({ status: 400, codigo: 'ITEM_SIN_CHASIS', linea: 2 });
    expect(m.st.productosCreados).toHaveLength(0);
    expect(m.st.movimientos).toHaveLength(0);
    expect(m.st.embarque.estado).toBe('DESPACHADO');
  });

  it('chasis de un producto existente lo usa (no crea otro); uno nuevo crea el producto', async () => {
    const m = mundo({ perfil: 'AUTOS', items: autos(['8AJBA3CD1N1234567', '9BWZZZ377VT004251']), productos: [producto('p-hilux', { cod_producto: '8AJBA3CD1N1234567' })] });
    const res: any = await m.liberar();
    expect(m.st.productosCreados.map((p) => p.cod_producto)).toEqual(['9BWZZZ377VT004251']);
    expect(m.st.stock.get('dep-1|p-hilux')?.cantidad_disponible).toBe(1);
    expect(m.st.items[0]).toMatchObject({ producto_id: 'p-hilux', estado: 'DISPONIBLE' });
    expect(res).toMatchObject({ productos_creados: 1, items_actualizados: 2 });
    const v = await m.service.vistaLiberacion('emb-1', EMPRESA, 'u-1');
    expect(v.lineas).toEqual([]); // LIBERADO: ya no hay qué liberar
  });

  it('la vista de AUTOS marca USA_PRODUCTO_EXISTENTE y CREA_PRODUCTO', async () => {
    const m = mundo({ perfil: 'AUTOS', items: autos(['8AJBA3CD1N1234567', '9BWZZZ377VT004251']), productos: [producto('p-hilux', { cod_producto: '8AJBA3CD1N1234567' })] });
    const v = await m.vista('dep-1');
    expect(v.lineas.map((l) => [l.linea, l.efecto])).toEqual([
      [1, 'USA_PRODUCTO_EXISTENTE'],
      [2, 'CREA_PRODUCTO'],
    ]);
  });

  it('CONSUMO_MASIVO sin producto → SIN_PRODUCTO_MAPEADO linea 2; cantidad 0 → CANTIDAD_INVALIDA', async () => {
    const m = mundo({ items: [itemCm('it-1', 'p1'), itemCm('it-2', null)] });
    expect(await m.error(m.liberar())).toMatchObject({ status: 400, codigo: 'SIN_PRODUCTO_MAPEADO', linea: 2 });
    const m2 = mundo({ items: [itemCm('it-1', 'p1', { cantidad: 0 })] });
    expect(await m2.error(m2.liberar())).toMatchObject({ status: 400, codigo: 'CANTIDAD_INVALIDA', linea: 1 });
  });

  it('la linea sigue el orden de la pantalla (orden, created_at)', async () => {
    const m = mundo();
    await m.vista();
    const args = m.txs[0].imp_embarque_items.findMany.mock.calls[0][0];
    expect(args.orderBy).toEqual([{ orden: 'asc' }, { created_at: 'asc' }]);
  });
});

describe('liberar: alcance de depósitos (fila 22)', () => {
  it('depósito de otra sucursal con alcance restringido → DEPOSITO_FUERA_DE_ALCANCE (liberar y vista)', async () => {
    alcance.mockResolvedValue({ sucursalIds: ['suc-1'], puntosEstablecimiento: ['001'], depositoIds: ['dep-1'] });
    const m = mundo();
    expect(await m.error(m.liberar('dep-2'))).toMatchObject({ status: 400, codigo: 'DEPOSITO_FUERA_DE_ALCANCE', campo: 'deposito_destino_id' });
    expect(await m.error(m.vista('dep-2'))).toMatchObject({ status: 400, codigo: 'DEPOSITO_FUERA_DE_ALCANCE', campo: 'deposito_id' });
    expect(alcance).toHaveBeenCalledWith(expect.anything(), 'u-1', EMPRESA);
    expect(m.st.movimientos).toHaveLength(0);
    // el propio sí
    await expect(m.liberar('dep-1')).resolves.toMatchObject({ deposito_destino_id: 'dep-1' });
  });

  it('depósito inexistente o de otra empresa → DEPOSITO_FUERA_DE_ALCANCE', async () => {
    const m = mundo();
    expect(await m.error(m.liberar('dep-x'))).toMatchObject({ status: 400, codigo: 'DEPOSITO_FUERA_DE_ALCANCE' });
  });
});

describe('liberar: asiento del despacho (B1)', () => {
  it('con Contabilidad y asiento del despacho PENDIENTE → ASIENTO_DESPACHO_PENDIENTE; sin Contabilidad pasa', async () => {
    const pendiente = { id: 'des-1', estado: 'CONFIRMADO', asiento_estado: 'PENDIENTE', asiento_codigo: 'MAPEO_FALTANTE' };
    const con = mundo({ contabilidad: true, despacho: pendiente });
    expect(await con.error(con.liberar())).toMatchObject({ status: 409, codigo: 'ASIENTO_DESPACHO_PENDIENTE' });
    expect(con.st.movimientos).toHaveLength(0);

    const sin = mundo({ contabilidad: false, despacho: pendiente });
    await expect(sin.liberar()).resolves.toMatchObject({ message: 'Embarque liberado' });
  });

  it('con Contabilidad pasa con GENERADO (también la corrección manual) o NO_APLICA', async () => {
    for (const despacho of [
      { estado: 'CONFIRMADO', asiento_estado: 'GENERADO', asiento_codigo: 'CORRECCION_MANUAL' },
      { estado: 'CONFIRMADO', asiento_estado: 'NO_APLICA', asiento_codigo: null },
    ]) {
      const m = mundo({ contabilidad: true, despacho });
      await expect(m.liberar()).resolves.toMatchObject({ message: 'Embarque liberado' });
    }
  });
});

describe('liberar: lotes (fila 20, F25)', () => {
  const conLote = () => ({ productos: [producto('p1'), producto('p2', { maneja_lote: true, descripcion: 'Aceite 1L' })] });

  it('vista y liberar coinciden para producto con lote en sucursal sin lotes', async () => {
    // dep-1 = suc-1 sin lotes; dep-3 sin sucursal
    for (const deposito of ['dep-1', 'dep-3']) {
      const m = mundo({ ...conLote(), sucursalesConLotes: ['suc-2'] });
      const v = await m.vista(deposito);
      expect(v.deposito).toMatchObject({ id: deposito, usa_lotes: false });
      expect(v.lineas[1]).toMatchObject({ pide_lote: false, efecto: 'ENTRA_STOCK' });
      await m.liberar(deposito);
      expect(m.lotesService.createLoteIngreso).not.toHaveBeenCalled();
      expect(m.st.movimientos.every((mv) => mv.lote_id === null)).toBe(true);
    }
    // y en la sucursal con lotes los dos piden y crean lote
    const m = mundo({ ...conLote(), sucursalesConLotes: ['suc-2'] });
    const v = await m.vista('dep-2');
    expect(v.lineas[1]).toMatchObject({ pide_lote: true, efecto: 'CREA_LOTE' });
    await m.liberar('dep-2');
    expect(m.lotesService.createLoteIngreso).toHaveBeenCalledTimes(1);
    expect(m.st.movimientos.find((mv) => mv.producto_id === 'p2')?.lote_id).toBe('lote-1');
  });

  it('lote vence antes → LOTE_VENCE_ANTES con linea, sin escribir', async () => {
    const m = mundo({ ...conLote(), sucursalesConLotes: ['suc-1'] });
    const e = await m.error(m.liberar('dep-1', [{ item_id: 'it-2', fecha_fabricacion: '2026-10-01', fecha_vencimiento: '2026-09-01' }]));
    expect(e).toMatchObject({ status: 400, codigo: 'LOTE_VENCE_ANTES', linea: 2, campo: 'fecha_vencimiento' });
    expect(m.st.movimientos).toHaveLength(0);
  });

  it('número de lote que el producto ya tiene → LOTE_DUPLICADO con linea', async () => {
    const m = mundo({ ...conLote(), sucursalesConLotes: ['suc-1'], lotes: [{ id: 'l-viejo', empresa_id: EMPRESA, producto_id: 'p2', numero_lote: 'A-77' }] });
    const e = await m.error(m.liberar('dep-1', [{ item_id: 'it-2', numero_lote: ' A-77 ' }]));
    expect(e).toMatchObject({ status: 400, codigo: 'LOTE_DUPLICADO', linea: 2, campo: 'numero_lote' });
    expect(String(e.message)).toMatch(/Aceite 1L/);
  });

  it('el mismo número para dos líneas del mismo producto → LOTE_DUPLICADO en la segunda', async () => {
    const m = mundo({ items: [itemCm('it-1', 'p2'), itemCm('it-2', 'p2', { cantidad: 3 })], productos: [producto('p2', { maneja_lote: true })], sucursalesConLotes: ['suc-1'] });
    const e = await m.error(
      m.liberar('dep-1', [
        { item_id: 'it-1', numero_lote: 'B-1' },
        { item_id: 'it-2', numero_lote: 'B-1' },
      ]),
    );
    expect(e).toMatchObject({ status: 400, codigo: 'LOTE_DUPLICADO', linea: 2 });
  });

  it('datos de lote de un ítem ajeno → DATOS_CAMBIADOS', async () => {
    const m = mundo();
    expect(await m.error(m.liberar('dep-1', [{ item_id: 'otro' }]))).toMatchObject({ status: 409, codigo: 'DATOS_CAMBIADOS' });
  });
});

describe('liberar: producto sin inventario (fila 21)', () => {
  it('producto sin inventario: disponible y evento', async () => {
    const m = mundo({ productos: [producto('p1'), producto('p2', { maneja_inventario: false, descripcion: 'Servicio de armado' })] });
    const res: any = await m.liberar();

    expect(m.st.stock.has('dep-1|p2')).toBe(false);
    expect(m.st.movimientos.map((mv) => mv.producto_id)).toEqual(['p1']);
    expect(m.st.items[1]).toMatchObject({ estado: 'DISPONIBLE', producto_id: 'p2' });
    const evento = m.st.bitacora.find((b) => b.evento === 'LIBERADO_SIN_INVENTARIO');
    expect(evento?.detalle).toMatchObject({
      items: [expect.objectContaining({ linea: 2, item_id: 'it-2', producto: expect.objectContaining({ descripcion: 'Servicio de armado' }) })],
    });
    expect(res).toMatchObject({ sin_inventario: 1, items_actualizados: 1 });
  });
});

describe('vista previa (GET …/liberacion)', () => {
  it('vista previa con costo unitario de entrada y efecto', async () => {
    const m = mundo({ productos: [producto('p1', { maneja_lote: true }), producto('p2', { maneja_inventario: false })], sucursalesConLotes: ['suc-1'] });
    const v = await m.vista('dep-1');
    expect(v).toEqual({
      deposito: { id: 'dep-1', descripcion: 'Central', usa_lotes: true },
      lineas: [
        {
          linea: 1,
          item_id: 'it-1',
          producto: { id: 'p1', codigo: 'COD-p1', descripcion: 'Producto p1' },
          cantidad: '10',
          costo_unitario: '1500.00',
          efecto: 'CREA_LOTE',
          pide_lote: true,
        },
        {
          linea: 2,
          item_id: 'it-2',
          producto: { id: 'p2', codigo: 'COD-p2', descripcion: 'Producto p2' },
          cantidad: '4',
          costo_unitario: '800.50',
          efecto: 'SIN_INVENTARIO',
          pide_lote: false,
        },
      ],
      errores: [],
    });
    // no escribe ni toma el lock
    expect(m.st.movimientos).toHaveLength(0);
    expect(m.txs[0].$executeRaw).not.toHaveBeenCalled();
  });

  it('sin deposito_id: solo líneas, sin pide_lote; con errores bloqueantes', async () => {
    const m = mundo({ items: [itemCm('it-1', 'p1'), itemCm('it-2', null)] });
    const v = await m.vista();
    expect(v.deposito).toBeNull();
    expect('pide_lote' in v.lineas[0]).toBe(false);
    expect(v.errores).toEqual([expect.objectContaining({ codigo: 'SIN_PRODUCTO_MAPEADO', linea: 2 })]);
  });

  it('en LIBERADO devuelve lo que saldría al revertir (salidas)', async () => {
    const m = mundo({ productos: [producto('p1'), producto('p2', { maneja_lote: true })], sucursalesConLotes: ['suc-1'] });
    await m.liberar('dep-1', [{ item_id: 'it-2', numero_lote: 'A-1' }]);
    const v: any = await m.vista();
    expect(v.salidas).toEqual([
      { producto: { id: 'p1', codigo: 'COD-p1', descripcion: 'Producto p1' }, cantidad: '10', lote: null },
      { producto: { id: 'p2', codigo: 'COD-p2', descripcion: 'Producto p2' }, cantidad: '4', lote: { id: 'lote-1', numero_lote: 'A-1' } },
    ]);
  });
});

describe('revertir con códigos', () => {
  it('revertir devuelve las salidas y deja el embarque DESPACHADO con el stock en cero', async () => {
    const m = mundo();
    await m.liberar();
    const res: any = await m.revertir();
    expect(res.salidas).toEqual([
      { producto: { id: 'p1', codigo: 'COD-p1', descripcion: 'Producto p1' }, cantidad: '10', lote: null },
      { producto: { id: 'p2', codigo: 'COD-p2', descripcion: 'Producto p2' }, cantidad: '4', lote: null },
    ]);
    expect(m.st.embarque.estado).toBe('DESPACHADO');
    expect(m.st.stock.get('dep-1|p1')?.cantidad_disponible).toBe(0);
    expect(m.st.bitacora.find((b) => b.evento === 'LIBERACION_REVERTIDA')?.observacion).toBe('Se liberó al depósito equivocado');
  });

  it('dos reversiones: la segunda relee bajo imp: y recibe ESTADO_CAMBIADO; el stock sale una vez', async () => {
    const m = mundo();
    await m.liberar();
    const [a, b] = await Promise.allSettled([m.revertir(), m.revertir()]);
    expect(a.status).toBe('fulfilled');
    expect((b as PromiseRejectedResult).reason.getResponse()).toMatchObject({ codigo: 'ESTADO_CAMBIADO', estado_actual: 'DESPACHADO' });
    expect(m.st.stock.get('dep-1|p1')?.cantidad_disponible).toBe(0);
  });

  it('revertir con unidades vendidas → REVERSION_CON_SALIDAS', async () => {
    const m = mundo();
    await m.liberar();
    m.st.movimientos.push({ producto_id: 'p1', deposito_origen_id: 'dep-1', cantidad: 2, salida: true, created_at: new Date(Date.now() + 1000) });
    expect(await m.error(m.revertir())).toMatchObject({ status: 409, codigo: 'REVERSION_CON_SALIDAS' });
    expect(m.st.embarque.estado).toBe('LIBERADO');
  });

  it('lote parcial → LOTE_NO_INTEGRO', async () => {
    const m = mundo({ productos: [producto('p1'), producto('p2', { maneja_lote: true })], sucursalesConLotes: ['suc-1'] });
    await m.liberar();
    m.st.lotes[0].en_deposito = 1;
    expect(await m.error(m.revertir())).toMatchObject({ status: 409, codigo: 'LOTE_NO_INTEGRO' });
  });

  it('stock reservado → STOCK_INSUFICIENTE', async () => {
    const m = mundo();
    await m.liberar();
    (m.st.stock.get('dep-1|p1') as { cantidad_reservada: number }).cantidad_reservada = 3;
    expect(await m.error(m.revertir())).toMatchObject({ status: 409, codigo: 'STOCK_INSUFICIENTE' });
  });

  it('motivo en blanco → CAMPO_REQUERIDO con campo motivo (sin texto inventado)', async () => {
    const m = mundo();
    await m.liberar();
    expect(await m.error(m.revertir('   '))).toMatchObject({ status: 400, codigo: 'CAMPO_REQUERIDO', campo: 'motivo' });
    expect(m.st.embarque.estado).toBe('LIBERADO');
  });

  it('desde CERRADO → ESTADO_CAMBIADO', async () => {
    const m = mundo({ estado: 'CERRADO' });
    expect(await m.error(m.revertir())).toMatchObject({ status: 409, codigo: 'ESTADO_CAMBIADO', estado_actual: 'CERRADO' });
  });
});

describe('controller', () => {
  const proto = ImportacionesController.prototype as any;

  it('GET embarques/:id/liberacion con IMP_EMB_EMBARQUE_CERRAR y el usuario para el alcance', async () => {
    expect(Reflect.getMetadata(REQUIRE_PERMISSION_KEY, proto.vistaLiberacion)).toEqual({ modulo: 'IMPORTACIONES', privilegio: 'IMP_EMB_EMBARQUE_CERRAR' });
    expect(Reflect.getMetadata(REQUIRE_SUBMODULO_KEY, proto.vistaLiberacion)).toBe('IMP_EMBARQUES');
    expect(Reflect.getMetadata('path', proto.vistaLiberacion)).toBe('embarques/:id/liberacion');
    const service: any = { vistaLiberacion: jest.fn(), liberarEmbarque: jest.fn() };
    const ctrl = new ImportacionesController(service, {} as any, {} as any);
    const user: any = { id: 'u-1', empresa_id: EMPRESA };
    await ctrl.vistaLiberacion('emb-1', user, 'dep-1');
    expect(service.vistaLiberacion).toHaveBeenCalledWith('emb-1', EMPRESA, 'u-1', 'dep-1');
    await ctrl.liberarEmbarque('emb-1', { deposito_destino_id: 'dep-1' } as any, user);
    expect(service.liberarEmbarque).toHaveBeenCalledWith('emb-1', { deposito_destino_id: 'dep-1' }, EMPRESA, 'u-1');
  });

  it('el cuerpo de liberar sigue siendo deposito_destino_id + lotes (F15)', async () => {
    const pipe = new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true });
    const dto = await pipe.transform(
      { deposito_destino_id: '7f1e6c4a-1b2c-4d5e-8f90-123456789abc', lotes: [{ item_id: '7f1e6c4a-1b2c-4d5e-8f90-123456789abd', numero_lote: 'A-1' }] },
      { type: 'body', metatype: LiberarEmbarqueDto },
    );
    expect(dto.lotes?.[0].numero_lote).toBe('A-1');
  });
});

describe('liberar: bloqueo ordenado contra el cierre de inventario (ola 3 de Existencias)', () => {
  it('bloquea lotes y stock de todas las líneas con inventario en un solo pase, antes de la primera escritura de stock', async () => {
    const m = mundo({
      items: [itemCm('it-1', 'p2'), itemCm('it-2', 'p1', { cantidad: 4 }), itemCm('it-3', 'p3', { cantidad: 2 })],
      productos: [producto('p1'), producto('p2'), producto('p3', { maneja_inventario: false })],
    });
    const bloquear = jest.spyOn(m.lotesService, 'bloquearStockDe');
    await m.liberar();

    expect(bloquear).toHaveBeenCalledTimes(1);
    const [, empresa, pares] = bloquear.mock.calls[0] as [unknown, string, Array<{ productoId: string; depositoId: string }>];
    expect(empresa).toBe(EMPRESA);
    // Las líneas sin inventario no escriben stock: no se bloquean.
    expect(pares).toEqual([
      { productoId: 'p2', depositoId: 'dep-1' },
      { productoId: 'p1', depositoId: 'dep-1' },
    ]);
    const tx = m.txs[0];
    expect(bloquear.mock.invocationCallOrder[0]).toBeLessThan(tx.stock_deposito.upsert.mock.invocationCallOrder[0]);
    // El comportamiento no cambia: cada línea suma lo suyo.
    expect(m.st.stock.get('dep-1|p2')?.cantidad_disponible).toBe(10);
    expect(m.st.stock.get('dep-1|p1')?.cantidad_disponible).toBe(4);
  });
});
