import { ImportacionesService } from './importaciones.service';

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

/**
 * S6: «Revertir liberación» de una importación mientras su mercadería no se movió.
 */
describe('ImportacionesService - revertir liberación (S6)', () => {
  const liberadoEn = new Date('2026-10-20T10:00:00Z');

  const crear = (
    opts: {
      estado?: string;
      salidas?: Array<{ producto_id: string }>;
      stock?: { cantidad_disponible: number; cantidad_reservada: number };
      usaLotes?: boolean;
      sinLote?: number;
      movimientos?: any[];
      lote?: { total: number; enDeposito: number };
    } = {},
  ) => {
    const tx: any = {
      $executeRaw: jest.fn(),
      imp_config_empresa: { findUnique: jest.fn().mockResolvedValue({ empresa_id: 'emp-1', modulo_operativo_activo: true, perfil_activo: 'AUTOS' }) },
      imp_embarques: { findFirst: jest.fn().mockResolvedValue({ id: 'emb-1', numero: 'IMP-0007', estado: opts.estado ?? 'LIBERADO' }), update: jest.fn() },
      movimientos_inventario: {
        findMany: jest
          .fn()
          .mockResolvedValueOnce(
            opts.movimientos ?? [
              {
                producto_id: 'p1',
                deposito_origen_id: 'dep-1',
                cantidad: 10,
                costo_unitario: 1500,
                documento_origen: 'IMP',
                created_at: liberadoEn,
                producto: { descripcion: 'Neumático 15"' },
              },
            ],
          )
          .mockResolvedValueOnce(opts.salidas ?? []),
        create: jest.fn(),
      },
      tipo_movimiento_inventario: { findMany: jest.fn().mockResolvedValue([{ id: 't-venta' }]) },
      stock_deposito: { findUnique: jest.fn().mockResolvedValue(opts.stock ?? { cantidad_disponible: 10, cantidad_reservada: 0 }), update: jest.fn() },
      imp_embarque_items: { updateMany: jest.fn().mockResolvedValue({ count: 3 }) },
      lotes_producto: { findUnique: jest.fn().mockResolvedValue({ cantidad_disponible: opts.lote?.total ?? 10 }) },
      stock_lote: { findUnique: jest.fn().mockResolvedValue({ cantidad_disponible: opts.lote?.enDeposito ?? 10 }) },
      imp_embarques_bitacora: { create: jest.fn() },
    };
    const prisma: any = { $transaction: jest.fn(async (cb: any) => cb(tx)) };
    const lotesService: any = { usaLotesEnDeposito: jest.fn().mockResolvedValue(opts.usaLotes ?? false), descontarDeLote: jest.fn(), bloquearStockDe: jest.fn() };
    const fifoService: any = { cantidadSinLote: jest.fn().mockResolvedValue(opts.sinLote ?? 0) };
    const service = new ImportacionesService(prisma, {} as any, {} as any, {} as any, {} as any, lotesService, fifoService);
    const revertir = () => service.revertirLiberacion('emb-1', { motivo: 'Depósito equivocado' }, 'emp-1', 'u-1');
    return { tx, lotesService, revertir };
  };

  const movConLote = {
    producto_id: 'p1',
    deposito_origen_id: 'dep-1',
    lote_id: 'lote-1',
    lote: { numero_lote: 'L20261020-001' },
    cantidad: 10,
    costo_unitario: 1500,
    documento_origen: 'IMP',
    created_at: liberadoEn,
    producto: { descripcion: 'Aceite 1L' },
  };

  it('saca del depósito lo que entró, con ANUL_IMPORTACION, y vuelve a DESPACHADO', async () => {
    const { tx, revertir } = crear();
    const res = await revertir();

    expect(tx.stock_deposito.update).toHaveBeenCalledWith({
      where: { deposito_id_producto_id: { deposito_id: 'dep-1', producto_id: 'p1' } },
      data: expect.objectContaining({ cantidad_disponible: { decrement: 10 } }),
    });
    expect(tx.movimientos_inventario.create).toHaveBeenCalledWith({
      data: expect.objectContaining({ tipo_movimiento_id: 'tipo-ANUL_IMPORTACION', cantidad: 10, costo_unitario: 1500, documento_origen: 'IMP_REVERSA', documento_id: 'emb-1' }),
    });
    expect(tx.imp_embarque_items.updateMany).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ estado: 'PENDIENTE' }) }));
    expect(tx.imp_embarques.update).toHaveBeenCalledWith({ where: { id: 'emb-1' }, data: expect.objectContaining({ estado: 'DESPACHADO' }) });
    expect(tx.imp_embarques_bitacora.create).toHaveBeenCalledWith({ data: expect.objectContaining({ evento: 'LIBERACION_REVERTIDA', observacion: 'Depósito equivocado' }) });
    expect(res.productos_revertidos).toBe(1);
  });

  it('pide la descripción por la relación `producto` de movimientos_inventario (la que existe en Prisma)', async () => {
    const { tx, revertir } = crear();
    await revertir();
    const select = tx.movimientos_inventario.findMany.mock.calls[0][0].select;
    expect(select.producto).toEqual({ select: { id: true, cod_producto: true, descripcion: true } });
    expect(select).not.toHaveProperty('productos');
  });

  it('solo desde LIBERADO', async () => {
    const { revertir } = crear({ estado: 'CERRADO' });
    await expect(revertir()).rejects.toMatchObject({
      response: { codigo: 'ESTADO_CAMBIADO', estado_actual: 'CERRADO', message: expect.stringMatching(/Primero volvé el expediente a Liberado/) },
    });
  });

  it('rechaza si después de liberar ya salió mercadería', async () => {
    const { tx, revertir } = crear({ salidas: [{ producto_id: 'p1' }] });
    await expect(revertir()).rejects.toMatchObject({ response: { codigo: 'REVERSION_CON_SALIDAS', message: expect.stringMatching(/ya salió mercadería de Neumático/) } });
    expect(tx.stock_deposito.update).not.toHaveBeenCalled();
  });

  it('rechaza si el stock libre no alcanza (reservado)', async () => {
    const { revertir } = crear({ stock: { cantidad_disponible: 10, cantidad_reservada: 4 } });
    await expect(revertir()).rejects.toMatchObject({ status: 409, response: { codigo: 'STOCK_INSUFICIENTE' } });
  });

  it('con lotes, solo cuenta el stock sin lote', async () => {
    const { revertir } = crear({ usaLotes: true, sinLote: 6 });
    await expect(revertir()).rejects.toMatchObject({ response: { codigo: 'STOCK_INSUFICIENTE', message: expect.stringMatching(/hay 6 libre/) } });
  });

  it('descuenta reversiones anteriores: solo revierte lo que sigue liberado', async () => {
    const { tx, revertir } = crear({
      movimientos: [
        {
          producto_id: 'p1',
          deposito_origen_id: 'dep-1',
          cantidad: 10,
          costo_unitario: 1500,
          documento_origen: 'IMP',
          created_at: new Date('2026-10-01'),
          producto: { descripcion: 'X' },
        },
        {
          producto_id: 'p1',
          deposito_origen_id: 'dep-1',
          cantidad: 10,
          costo_unitario: 1500,
          documento_origen: 'IMP_REVERSA',
          created_at: new Date('2026-10-02'),
          producto: { descripcion: 'X' },
        },
        { producto_id: 'p1', deposito_origen_id: 'dep-1', cantidad: 8, costo_unitario: 1600, documento_origen: 'IMP', created_at: liberadoEn, producto: { descripcion: 'X' } },
      ],
    });
    await revertir();
    expect(tx.movimientos_inventario.create).toHaveBeenCalledTimes(1);
    expect(tx.movimientos_inventario.create.mock.calls[0][0].data).toEqual(expect.objectContaining({ cantidad: 8, costo_unitario: 1600 }));
    // las salidas se buscan desde la última liberación
    expect(tx.movimientos_inventario.findMany.mock.calls[1][0].where.created_at).toEqual({ gt: liberadoEn });
  });

  it('cambiar el estado a mano de LIBERADO a DESPACHADO se bloquea', async () => {
    const { tx } = crear();
    tx.$executeRaw = jest.fn();
    const service = new ImportacionesService({ $transaction: jest.fn(async (cb: any) => cb(tx)) } as any, {} as any, {} as any, {} as any, {} as any, {} as any, {} as any);
    await expect(service.updateEstado('emb-1', { estado: 'DESPACHADO' } as any, 'emp-1', 'u-1')).rejects.toMatchObject({
      response: { codigo: 'TRANSICION_NO_PERMITIDA', estado_actual: 'LIBERADO', estado_pedido: 'DESPACHADO' },
    });
  });

  it('saca el lote que creó la liberación si está íntegro (y no exige stock sin lote)', async () => {
    const { tx, lotesService, revertir } = crear({ movimientos: [movConLote], usaLotes: true, sinLote: 0 });
    const res = await revertir();
    expect(lotesService.descontarDeLote).toHaveBeenCalledWith(tx, { loteId: 'lote-1', depositoId: 'dep-1', cantidad: 10 });
    expect(tx.movimientos_inventario.create).toHaveBeenCalledWith({ data: expect.objectContaining({ lote_id: 'lote-1', documento_origen: 'IMP_REVERSA', cantidad: 10 }) });
    expect(tx.imp_embarque_items.updateMany).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ lote_id: null, estado: 'PENDIENTE' }) }));
    expect(res.lotes_revertidos).toBe(1);
  });

  it('rechaza si el lote ya tuvo salidas', async () => {
    const { tx, lotesService, revertir } = crear({ movimientos: [movConLote], usaLotes: true, lote: { total: 7, enDeposito: 7 } });
    await expect(revertir()).rejects.toMatchObject({
      response: { codigo: 'LOTE_NO_INTEGRO', message: expect.stringMatching(/el lote L20261020-001 de Aceite 1L ya no está completo/) },
    });
    expect(lotesService.descontarDeLote).not.toHaveBeenCalled();
    expect(tx.stock_deposito.update).not.toHaveBeenCalled();
  });

  it('rechaza si parte del lote se trasladó a otro depósito', async () => {
    const { revertir } = crear({ movimientos: [movConLote], usaLotes: true, lote: { total: 10, enDeposito: 6 } });
    await expect(revertir()).rejects.toMatchObject({ response: { codigo: 'LOTE_NO_INTEGRO', message: expect.stringMatching(/hoy tiene 6 en el depósito y 10 en total/) } });
  });
  it('bloquea lotes y stock de todo lo que revierte, en el orden del cierre de inventario, antes de leer o escribir stock', async () => {
    const mov = (producto_id: string, lote_id: string | null) => ({ ...movConLote, producto_id, lote_id, lote: lote_id ? { numero_lote: lote_id } : null });
    const { tx, lotesService, revertir } = crear({ movimientos: [mov('p2', 'lote-b'), mov('p1', 'lote-a')], usaLotes: true, sinLote: 0 });
    await revertir();
    expect(lotesService.bloquearStockDe).toHaveBeenCalledTimes(1);
    expect(lotesService.bloquearStockDe).toHaveBeenCalledWith(tx, 'emp-1', [
      { productoId: 'p2', depositoId: 'dep-1' },
      { productoId: 'p1', depositoId: 'dep-1' },
    ]);
    const bloqueo = lotesService.bloquearStockDe.mock.invocationCallOrder[0];
    // Las validaciones (lote íntegro, stock libre) leen ya bajo el bloqueo, y ninguna escritura va antes.
    for (const f of [tx.lotes_producto.findUnique, tx.stock_lote.findUnique, tx.stock_deposito.findUnique, lotesService.descontarDeLote, tx.stock_deposito.update]) {
      expect(f.mock.invocationCallOrder[0]).toBeGreaterThan(bloqueo);
    }
  });
});
