import { ComprasService } from './compras.service';

/**
 * La factura que llega después de la recepción corrige el costo: los lotes que
 * creó la recepción (con el precio de la OC) y el costo del producto pasan al
 * costo neto real de la factura, con auditoría y costo anterior para S7.
 */
describe('ComprasService.aplicarCostoFacturaARecepciones', () => {
  const item = (over: any = {}) => ({
    producto_id: 'p1',
    orden_compra_det_id: 'ocd-1',
    costo_unitario_neto: 1200,
    ...over,
  });
  const crearTx = (over: any = {}) => ({
    recepcion_compra_det: { findMany: jest.fn().mockResolvedValue([{ lote_id: 'l1' }, { lote_id: 'l1' }, { lote_id: null }]) },
    lotes_producto: {
      findFirst: jest.fn().mockResolvedValue({ id: 'l1', numero_lote: 'L-1', costo_unitario: 1000 }),
      update: jest.fn(),
    },
    productos: { findUnique: jest.fn().mockResolvedValue({ descripcion: 'Licuadora', precio_costo: 1000 }), update: jest.fn() },
    compra_det: { update: jest.fn() },
    audit_logs: { create: jest.fn() },
    compra_costo_lote: { create: jest.fn(), findMany: jest.fn().mockResolvedValue([]), deleteMany: jest.fn() },
    ...over,
  });
  const service = new ComprasService({} as any, {} as any, {} as any, {} as any, {} as any, {} as any, { logEnTransaccion: jest.fn() } as any);
  const aplicar = (tx: any, items: any[] = [item()]) =>
    (service as any).aplicarCostoFacturaARecepciones(tx, {
      empresaId: 'emp',
      compraId: 'c1',
      items,
      detalles: items.map((_, i) => ({ id: `det-${i}`, producto_id: 'p1' })),
      usuarioId: 'u1',
      numeroComprobante: '001-001-0000123',
    });

  it('corrige el costo del lote y del producto, guarda el costo anterior y audita', async () => {
    const tx: any = crearTx();
    const r = await aplicar(tx);
    expect(r).toEqual({ lotes: 1, productos: 1 });
    expect(tx.recepcion_compra_det.findMany).toHaveBeenCalledWith(
      expect.objectContaining({
        where: {
          orden_compra_det_id: 'ocd-1',
          recepcion_compra_cab: { empresa_id: 'emp', NOT: [{ anulado: true }, { estado: 'anulada' }] },
        },
      }),
    );
    expect(tx.lotes_producto.update).toHaveBeenCalledTimes(1);
    expect(tx.lotes_producto.update).toHaveBeenCalledWith(expect.objectContaining({ where: { id: 'l1' }, data: expect.objectContaining({ costo_unitario: 1200 }) }));
    expect(tx.productos.update).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ precio_costo: 1200 }) }));
    expect(tx.compra_det.update).toHaveBeenCalledWith({ where: { id: 'det-0' }, data: { costo_anterior: 1000 } });
    expect(tx.audit_logs.create).toHaveBeenCalledTimes(2);
    expect(tx.audit_logs.create.mock.calls[0][0].data).toEqual(
      expect.objectContaining({ entity_type: 'lote', old_value: { costo_unitario: 1000 }, new_value: { costo_unitario: 1200, compra_id: 'c1' } }),
    );
  });

  it('sin recepción no hay lotes que corregir, pero el producto toma el costo de la factura', async () => {
    const tx: any = crearTx({ recepcion_compra_det: { findMany: jest.fn().mockResolvedValue([]) } });
    expect(await aplicar(tx)).toEqual({ lotes: 0, productos: 1 });
    expect(tx.lotes_producto.update).not.toHaveBeenCalled();
    expect(tx.productos.update).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ precio_costo: 1200 }) }));
  });

  it('si el costo ya es el de la factura no audita cambios', async () => {
    const tx: any = crearTx({
      lotes_producto: { findFirst: jest.fn().mockResolvedValue({ id: 'l1', numero_lote: 'L-1', costo_unitario: 1200 }), update: jest.fn() },
      productos: { findUnique: jest.fn().mockResolvedValue({ descripcion: 'X', precio_costo: 1200 }), update: jest.fn() },
    });
    expect(await aplicar(tx)).toEqual({ lotes: 0, productos: 0 });
    expect(tx.audit_logs.create).not.toHaveBeenCalled();
  });

  it('líneas sin OC (factura libre) se ignoran', async () => {
    const tx: any = crearTx();
    await aplicar(tx, [item({ orden_compra_det_id: null })]);
    expect(tx.recepcion_compra_det.findMany).not.toHaveBeenCalled();
  });

  it('guarda el costo previo del lote para poder restaurarlo', async () => {
    const tx: any = crearTx();
    await aplicar(tx);
    expect(tx.compra_costo_lote.create).toHaveBeenCalledWith({
      data: { compra_id: 'c1', lote_id: 'l1', costo_anterior: 1000, costo_aplicado: 1200 },
    });
  });

  it('1.000 → factura 1.200 → anular: el lote vuelve a 1.000 (con auditoría)', async () => {
    // Base en memoria: el lote arranca en 1.000 (precio de la OC).
    const lote = { id: 'l1', numero_lote: 'L-1', costo_unitario: 1000 };
    const registros: any[] = [];
    const tx: any = crearTx({
      lotes_producto: {
        findFirst: jest.fn(async () => ({ ...lote })),
        update: jest.fn(async ({ data }: any) => {
          lote.costo_unitario = Number(data.costo_unitario);
        }),
      },
      compra_costo_lote: {
        create: jest.fn(async ({ data }: any) => registros.push({ ...data, created_at: new Date() })),
        findMany: jest.fn(async ({ where }: any) => registros.filter((r) => r.compra_id === where.compra_id)),
        deleteMany: jest.fn(async ({ where }: any) => {
          for (let i = registros.length - 1; i >= 0; i--) if (registros[i].compra_id === where.compra_id) registros.splice(i, 1);
        }),
      },
    });
    await aplicar(tx);
    expect(lote.costo_unitario).toBe(1200);

    const restaurados = await (service as any).restaurarCostoLotesDeFactura(tx, {
      empresaId: 'emp',
      compraId: 'c1',
      usuarioId: 'u1',
      numeroComprobante: '001-001-0000123',
    });
    expect(restaurados).toBe(1);
    expect(lote.costo_unitario).toBe(1000);
    expect(registros).toHaveLength(0);
    const auditoria = tx.audit_logs.create.mock.calls.map((c: any[]) => c[0].data);
    expect(auditoria).toEqual(
      expect.arrayContaining([
        expect.objectContaining({ entity_type: 'lote', old_value: { costo_unitario: 1200 }, new_value: { costo_unitario: 1000, compra_id: 'c1' } }),
      ]),
    );
  });

  it('al anular no pisa un costo que otra factura cambió después', async () => {
    const tx: any = crearTx({
      lotes_producto: { findFirst: jest.fn().mockResolvedValue({ id: 'l1', numero_lote: 'L-1', costo_unitario: 1300 }), update: jest.fn() },
      compra_costo_lote: {
        findMany: jest.fn().mockResolvedValue([{ lote_id: 'l1', costo_anterior: 1000, costo_aplicado: 1200 }]),
        deleteMany: jest.fn(),
      },
    });
    const n = await (service as any).restaurarCostoLotesDeFactura(tx, { empresaId: 'emp', compraId: 'c1' });
    expect(n).toBe(0);
    expect(tx.lotes_producto.update).not.toHaveBeenCalled();
    expect(tx.compra_costo_lote.deleteMany).toHaveBeenCalledWith({ where: { compra_id: 'c1' } });
  });
});
