import { BadRequestException } from '@nestjs/common';
import { RecepcionesCompraService } from './recepciones-compra.service';
import { LotesService } from 'src/lotes/lotes.service';

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

/**
 * LT5: la recepción de compra crea lotes igual que la factura de compra directa,
 * y al editarla o anularla revierte el lote íntegro.
 */
describe('RecepcionesCompraService - lotes en la recepción (LT5)', () => {
  const crear = (opts: { usaLotes?: boolean; existente?: any; lote?: any; prefijos?: string[]; factura?: any[] } = {}) => {
    const tx: any = {
      productos: {
        findMany: jest.fn().mockResolvedValue([
          { id: 'p1', descripcion: 'Yogur', maneja_inventario: true, precio_costo: 50 },
        ]),
      },
      orden_compra_det: {
        findMany: jest.fn().mockResolvedValue([{ id: 'od-1', precio_unitario: 70 }]),
      },
      compra_det: { findMany: jest.fn().mockResolvedValue(opts.factura ?? []) },
      compra_costo_lote: { create: jest.fn() },
      stock_deposito: { upsert: jest.fn() },
      movimientos_inventario: {
        create: jest.fn(),
        count: jest.fn().mockResolvedValue(1),
        // La reversa sale de los movimientos de entrada del documento.
        findMany: jest.fn().mockResolvedValue([
          { documento_origen: 'recepcion_compra', producto_id: 'p1', lote_id: 'lote-1', deposito_origen_id: 'dep-1', cantidad: 10 },
        ]),
      },
      recepcion_compra_det: { update: jest.fn() },
      lotes_producto: {
        findFirst: jest.fn().mockResolvedValue(opts.existente ?? null),
        findMany: jest.fn().mockResolvedValue((opts.prefijos ?? []).map((n) => ({ numero_lote: n }))),
        findUnique: jest.fn().mockResolvedValue(opts.lote ?? null),
      },
    };
    const lotesService: any = {
      usaLotesEnDeposito: jest.fn().mockResolvedValue(opts.usaLotes ?? true),
      createLoteIngreso: jest.fn().mockResolvedValue({ id: 'lote-nuevo' }),
      descontarDeLote: jest.fn(),
      bloquearStockDe: jest.fn(),
      generarNumeroLote: (...args: any[]) => (LotesService.prototype.generarNumeroLote as any).apply({}, args),
    };
    const service = new RecepcionesCompraService({} as any, {} as any, {} as any, lotesService);
    /** `lotesRevertidos`: ids de lotes de otro producto/número (no se reingresan, solo se excluyen del control de duplicados). */
    const aplicar = (detalles: any[], lotesRevertidos?: string[]) =>
      (service as any).aplicarStockRecepcion(tx, {
        empresaId: 'emp-1',
        recepcionId: 'rec-1',
        depositoId: 'dep-1',
        detalles,
        usuarioId: 'u-1',
        lotesRevertidos: lotesRevertidos?.map((loteId) => ({ loteId, productoId: 'otro', numeroLote: null, fechaFabricacion: null })),
      });
    const revertir = () => (service as any).revertirStockRecepcion(tx, { recepcionId: 'rec-1' });
    return { tx, lotesService, aplicar, revertir };
  };

  const linea = (extra: Record<string, unknown> = {}) => ({
    id: 'rd-1',
    orden_compra_det_id: 'od-1',
    producto_id: 'p1',
    cantidad_recibida: 10,
    ...extra,
  });

  it('si la factura de esa línea de OC ya está cargada, el lote toma su costo y se puede restaurar al anularla', async () => {
    const { tx, lotesService, aplicar } = crear({
      factura: [{ orden_compra_det_id: 'od-1', compra_id: 'c-9', cantidad: 10, subtotal: 900 }],
    });
    await aplicar([linea({ numero_lote: 'A-78' })]);
    expect(tx.compra_det.findMany).toHaveBeenCalledWith(
      expect.objectContaining({
        where: {
          orden_compra_det_id: { in: ['od-1'] },
          compra_cab: { empresa_id: 'emp-1', NOT: [{ anulado: true }, { activo: false }] },
        },
      }),
    );
    expect(lotesService.createLoteIngreso).toHaveBeenCalledWith(tx, expect.objectContaining({ costoUnitario: 90 }));
    expect(tx.compra_costo_lote.create).toHaveBeenCalledWith({
      data: { compra_id: 'c-9', lote_id: 'lote-nuevo', costo_anterior: 70, costo_aplicado: 90 },
    });
  });

  it('bloquea lotes y stock de todas las líneas, en el orden del cierre de inventario, antes de escribir stock', async () => {
    const { tx, lotesService, aplicar } = crear();
    tx.productos.findMany.mockResolvedValue([
      { id: 'p1', descripcion: 'Yogur', maneja_inventario: true, precio_costo: 50 },
      { id: 'p2', descripcion: 'Leche', maneja_inventario: true, precio_costo: 40 },
    ]);
    await aplicar([linea({ id: 'rd-2', producto_id: 'p2', numero_lote: 'B-1' }), linea({ numero_lote: 'A-1' })]);
    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];
    expect(tx.stock_deposito.upsert.mock.invocationCallOrder[0]).toBeGreaterThan(bloqueo);
    expect(lotesService.createLoteIngreso.mock.invocationCallOrder[0]).toBeGreaterThan(bloqueo);
  });

  it('crea el lote con el número y las fechas cargadas, al costo de la orden', async () => {
    const { tx, lotesService, aplicar } = crear();
    await aplicar([linea({ numero_lote: 'A-77', fecha_fabricacion: '2026-10-01', fecha_vencimiento: '2027-01-31' })]);

    expect(lotesService.createLoteIngreso).toHaveBeenCalledWith(
      tx,
      expect.objectContaining({
        productoId: 'p1',
        depositoId: 'dep-1',
        numeroLote: 'A-77',
        fechaFabricacion: new Date('2026-10-01T00:00:00.000Z'),
        fechaVencimiento: new Date('2027-01-31T00:00:00.000Z'),
        cantidad: 10,
        costoUnitario: 70,
      }),
    );
    expect(tx.recepcion_compra_det.update).toHaveBeenCalledWith({
      where: { id: 'rd-1' },
      data: expect.objectContaining({ lote_id: 'lote-nuevo', numero_lote: 'A-77' }),
    });
    expect(tx.movimientos_inventario.create).toHaveBeenCalledWith({
      data: expect.objectContaining({ lote_id: 'lote-nuevo', cantidad: 10, documento_origen: 'recepcion_compra' }),
    });
    expect(tx.stock_deposito.upsert).toHaveBeenCalledTimes(1);
  });

  it('sin número genera LYYYYMMDD-NNN siguiente al último del día', async () => {
    const { lotesService, aplicar } = crear({ prefijos: [] });
    await aplicar([linea()]);
    const numero = lotesService.createLoteIngreso.mock.calls[0][1].numeroLote as string;
    expect(numero).toMatch(/^L\d{8}-001$/);
  });

  it('sin orden de compra usa el costo actual del producto', async () => {
    const { lotesService, aplicar } = crear();
    await aplicar([linea({ orden_compra_det_id: null })]);
    expect(lotesService.createLoteIngreso.mock.calls[0][1].costoUnitario).toBe(50);
  });

  it('si el producto no usa lotes en el depósito, solo suma stock (sin lote)', async () => {
    const { tx, lotesService, aplicar } = crear({ usaLotes: false });
    await aplicar([linea({ numero_lote: 'A-77' })]);
    expect(lotesService.createLoteIngreso).not.toHaveBeenCalled();
    expect(tx.movimientos_inventario.create).toHaveBeenCalledWith({
      data: expect.objectContaining({ lote_id: null }),
    });
  });

  it('rechaza un número que el producto ya tiene', async () => {
    const { aplicar } = crear({ existente: { numero_lote: 'A-77', producto_id: 'p1' } });
    await expect(aplicar([linea({ numero_lote: 'A-77' })])).rejects.toThrow(/ya tiene un lote A-77/);
  });

  it('al editar, el número del lote revertido puede volver a usarse', async () => {
    const { tx, aplicar } = crear();
    await aplicar([linea({ numero_lote: 'A-77' })], ['lote-viejo']);
    expect(tx.lotes_producto.findFirst).toHaveBeenCalledWith(
      expect.objectContaining({ where: expect.objectContaining({ id: { notIn: ['lote-viejo'] } }) }),
    );
  });

  it('rechaza el mismo número dos veces para el producto en la recepción', async () => {
    const { aplicar } = crear();
    await expect(
      aplicar([linea({ numero_lote: 'A-77' }), linea({ id: 'rd-2', numero_lote: 'A-77' })]),
    ).rejects.toThrow(BadRequestException);
  });

  it('la reversa saca el lote íntegro y graba el movimiento con el lote', async () => {
    const { tx, lotesService, revertir } = crear({
      lote: {
        numero_lote: 'A-77',
        cantidad_inicial: 10,
        cantidad_disponible: 10,
        productos: { descripcion: 'Yogur' },
        stock_lote: [{ cantidad_disponible: 10 }],
      },
    });
    const revertidos = await revertir();
    expect(revertidos).toEqual([expect.objectContaining({ loteId: 'lote-1', productoId: 'p1', numeroLote: 'A-77' })]);
    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: 'recepcion_compra_reversa' }),
    });
  });

  it('no deja deshacer si del lote ya salieron unidades', async () => {
    const { tx, revertir } = crear({
      lote: {
        numero_lote: 'A-77',
        cantidad_inicial: 10,
        cantidad_disponible: 7,
        productos: { descripcion: 'Yogur' },
        stock_lote: [{ cantidad_disponible: 7 }],
      },
    });
    await expect(revertir()).rejects.toThrow(
      /del lote A-77 de Yogur ya salieron unidades/,
    );
    expect(tx.stock_deposito.upsert).not.toHaveBeenCalled();
  });
});
