import { MarangatuSyncService } from './marangatu-sync.service';

jest.mock('src/stock/tipos-movimiento-inventario', () => ({ tipoMovimientoInventarioId: jest.fn(async () => 'tipo-COMPRA') }));

/**
 * Ola 3 de Existencias: confirmar una compra de Marangatu suma stock renglón por renglón. Antes escribía cada `stock_deposito` en el
 * orden de los renglones y cruzaba con el cierre de inventario (40P01). Ahora toma todo en el orden del cierre
 * (`LotesService.bloquearStockDe`), una vez y antes de escribir.
 */
describe('MarangatuSyncService.confirmarCompra: bloqueo ordenado de stock', () => {
  it('bloquea los renglones con stock antes del primer stock_deposito y suma lo mismo que antes', async () => {
    const compra = {
      id: 'c1',
      empresa_id: 'emp',
      deposito_id: 'dep-1',
      plazo_credito: 30,
      observaciones: null,
      fecha_emision: new Date('2026-11-01T00:00:00Z'),
      establecimiento: '001',
      punto_expedicion: '001',
      numero_factura: '0000001',
      proveedor_id: 'prov',
      compra_det: [
        { producto_id: 'pB', afecta_stock: true, cantidad: 2, precio_unitario: 100, subtotal: 200, monto_iva: 18, porcentaje_iva: 10 },
        { producto_id: 'pA', afecta_stock: true, cantidad: 1, precio_unitario: 100, subtotal: 100, monto_iva: 9, porcentaje_iva: 10 },
        { producto_id: null, afecta_stock: true, cantidad: 1, precio_unitario: 50, subtotal: 50, monto_iva: 5, porcentaje_iva: 10 },
        { producto_id: 'pS', afecta_stock: false, cantidad: 1, precio_unitario: 50, subtotal: 50, monto_iva: 5, porcentaje_iva: 10 },
      ],
    };
    const tx: any = {
      $executeRaw: jest.fn().mockResolvedValue(1),
      compra_cab: { findFirst: jest.fn().mockResolvedValue({ estado: 'importado', compra_det: compra.compra_det }), update: jest.fn() },
      compra_subtotales: { deleteMany: jest.fn(), createMany: jest.fn() },
      cuentas_pagar: { deleteMany: jest.fn(), create: jest.fn().mockResolvedValue({ id: 'cxp-1' }) },
      stock_deposito: { upsert: jest.fn() },
      movimientos_inventario: { create: jest.fn() },
      productos: { update: jest.fn() },
    };
    const prisma: any = {
      compra_cab: { findFirst: jest.fn().mockResolvedValue(compra) },
      condicion_operacion: { findFirst: jest.fn().mockResolvedValue({ id: 'cond-2' }) },
      moneda: { findFirst: jest.fn().mockResolvedValue({ id: 'pyg' }) },
      depositos: { findFirst: jest.fn().mockResolvedValue({ id: 'dep-1', sucursal_id: 'suc-1' }) },
      $transaction: jest.fn(async (cb: (t: unknown) => Promise<unknown>) => cb(tx)),
    };
    const lotesService = { bloquearStockDe: jest.fn().mockResolvedValue(undefined) };
    const audit = { log: jest.fn() };
    const service = new MarangatuSyncService(prisma, {} as any, audit as any, {} as any, lotesService as any);

    await service.confirmarCompra('c1', 'emp', undefined, 'u1');

    expect(lotesService.bloquearStockDe).toHaveBeenCalledTimes(1);
    // El lock de la compra va primero, después la relectura del estado.
    expect(tx.$executeRaw.mock.invocationCallOrder[0]).toBeLessThan(tx.compra_cab.findFirst.mock.invocationCallOrder[0]);
    expect(lotesService.bloquearStockDe).toHaveBeenCalledWith(tx, 'emp', [
      { productoId: 'pB', depositoId: 'dep-1' },
      { productoId: 'pA', depositoId: 'dep-1' },
    ]);
    expect(lotesService.bloquearStockDe.mock.invocationCallOrder[0]).toBeLessThan(tx.stock_deposito.upsert.mock.invocationCallOrder[0]);
    expect(tx.stock_deposito.upsert.mock.calls.map((c: any[]) => [c[0].where.deposito_id_producto_id.producto_id, c[0].update.cantidad_disponible])).toEqual([
      ['pB', { increment: 2 }],
      ['pA', { increment: 1 }],
    ]);
  });

  it('dos confirmaciones a la vez: la segunda relee bajo el lock, ve la compra ya confirmada y responde 409 sin tocar nada', async () => {
    const compra = { id: 'c1', empresa_id: 'emp', deposito_id: 'dep-1', plazo_credito: 30, observaciones: null, fecha_emision: new Date(), compra_det: [
      { producto_id: 'pA', afecta_stock: true, cantidad: 1, precio_unitario: 100, subtotal: 100, monto_iva: 9, porcentaje_iva: 10 },
    ] };
    const tx: any = {
      $executeRaw: jest.fn().mockResolvedValue(1),
      compra_cab: { findFirst: jest.fn().mockResolvedValue({ estado: 'pendiente' }), update: jest.fn() },
      cuentas_pagar: { deleteMany: jest.fn(), create: jest.fn() },
      stock_deposito: { upsert: jest.fn() },
    };
    const prisma: any = {
      compra_cab: { findFirst: jest.fn().mockResolvedValue(compra) },
      condicion_operacion: { findFirst: jest.fn().mockResolvedValue({ id: 'cond-2' }) },
      moneda: { findFirst: jest.fn().mockResolvedValue({ id: 'pyg' }) },
      depositos: { findFirst: jest.fn().mockResolvedValue({ id: 'dep-1', sucursal_id: 'suc-1' }) },
      $transaction: jest.fn(async (cb: (t: unknown) => Promise<unknown>) => cb(tx)),
    };
    const audit = { log: jest.fn() };
    const service = new MarangatuSyncService(prisma, {} as any, audit as any, {} as any, { bloquearStockDe: jest.fn() } as any);
    const error: any = await service.confirmarCompra('c1', 'emp', undefined, 'u1').catch((e) => e);
    expect(error.getStatus()).toBe(409);
    expect(error.getResponse()).toMatchObject({ codigo: 'COMPRA_MARANGATU_YA_CONFIRMADA' });
    expect(tx.compra_cab.update).not.toHaveBeenCalled();
    expect(tx.cuentas_pagar.create).not.toHaveBeenCalled();
    expect(tx.stock_deposito.upsert).not.toHaveBeenCalled();
    expect(audit.log).not.toHaveBeenCalled();
  });

  /**
   * M4 (re-revisión de la ola 3): el estado se relee bajo `compra:`, pero los renglones (y con ellos totales, CxP y stock) salían de
   * la lectura de antes del lock. Si en el medio cambiaron, entraba el stock de la versión vieja. Ahora se releen bajo el lock y, si
   * no son los mismos, 409 DATOS_CAMBIADOS sin tocar nada.
   */
  it('M4: renglones cambiados entre la lectura y el lock → 409 DATOS_CAMBIADOS sin escribir', async () => {
    const det = [{ id: 'd1', producto_id: 'pA', afecta_stock: true, cantidad: 1, precio_unitario: 100, subtotal: 100, monto_iva: 9, porcentaje_iva: 10 }];
    const compra = { id: 'c1', empresa_id: 'emp', deposito_id: 'dep-1', plazo_credito: 30, observaciones: null, fecha_emision: new Date(), compra_det: det };
    const tx: any = {
      $executeRaw: jest.fn().mockResolvedValue(1),
      compra_cab: { findFirst: jest.fn().mockResolvedValue({ estado: 'importado', compra_det: [{ ...det[0], cantidad: 5, subtotal: 500 }] }), update: jest.fn() },
      compra_subtotales: { deleteMany: jest.fn(), createMany: jest.fn() },
      cuentas_pagar: { deleteMany: jest.fn(), create: jest.fn() },
      stock_deposito: { upsert: jest.fn() },
    };
    const prisma: any = {
      compra_cab: { findFirst: jest.fn().mockResolvedValue(compra) },
      condicion_operacion: { findFirst: jest.fn().mockResolvedValue({ id: 'cond-2' }) },
      moneda: { findFirst: jest.fn().mockResolvedValue({ id: 'pyg' }) },
      depositos: { findFirst: jest.fn().mockResolvedValue({ id: 'dep-1', sucursal_id: 'suc-1' }) },
      $transaction: jest.fn(async (cb: (t: unknown) => Promise<unknown>) => cb(tx)),
    };
    const service = new MarangatuSyncService(prisma, {} as any, { log: jest.fn() } as any, {} as any, { bloquearStockDe: jest.fn() } as any);
    const error: any = await service.confirmarCompra('c1', 'emp', undefined, 'u1').catch((e) => e);
    expect(error.getStatus?.()).toBe(409);
    expect(error.getResponse()).toMatchObject({ codigo: 'DATOS_CAMBIADOS' });
    expect(tx.compra_cab.update).not.toHaveBeenCalled();
    expect(tx.cuentas_pagar.create).not.toHaveBeenCalled();
    expect(tx.stock_deposito.upsert).not.toHaveBeenCalled();
  });
});
