import { LotesService } from 'src/lotes/lotes.service';
import { ImportacionesService } from './importaciones.service';

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

/**
 * Liberar un embarque con productos que manejan lotes: la mercadería entra en un
 * lote por línea (antes entraba sin lote).
 */
describe('ImportacionesService - liberar con lotes', () => {
  const crear = (opts: { usaLotes?: boolean; existente?: any; prefijos?: string[] } = {}) => {
    const items = [
      { id: 'it-1', producto_id: 'p1', sku_interno_id: null, cantidad: 10, costo_unitario_gs: 1500 },
      { id: 'it-2', producto_id: 'p2', sku_interno_id: null, cantidad: 4, costo_unitario_gs: 800 },
    ];
    const tx: any = {
      $executeRaw: jest.fn(),
      imp_despachos: { findFirst: jest.fn().mockResolvedValue({ asiento_estado: 'GENERADO' }) },
      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-0008', estado: 'DESPACHADO', perfil: 'CONSUMO_MASIVO' }), update: jest.fn() },
      depositos: { findFirst: jest.fn().mockResolvedValue({ id: 'dep-1', descripcion: 'Central', sucursal_id: 'suc-1' }) },
      imp_embarque_items: { findMany: jest.fn().mockResolvedValue(items), update: jest.fn() },
      productos: {
        // p1 maneja lote; p2 no
        findMany: jest.fn().mockResolvedValue([
          { id: 'p1', cod_producto: 'P1', descripcion: 'Aceite 1L', maneja_inventario: true, maneja_lote: true },
          { id: 'p2', cod_producto: 'P2', descripcion: 'Filtro', maneja_inventario: true, maneja_lote: false },
        ]),
      },
      stock_deposito: { upsert: jest.fn() },
      movimientos_inventario: { create: jest.fn() },
      lotes_producto: {
        findFirst: jest.fn().mockResolvedValue(opts.existente ?? null),
        findMany: jest.fn().mockResolvedValue((opts.prefijos ?? []).map((n) => ({ numero_lote: n }))),
      },
      imp_embarques_bitacora: { create: jest.fn() },
    };
    const prisma: any = { $transaction: jest.fn(async (cb: any) => cb(tx)) };
    let n = 0;
    const lotesService: any = {
      // la sucursal del depósito usa lotes (salvo que se pida lo contrario); el producto lo decide la vista (F25)
      depositoUsaLotes: jest.fn(async () => opts.usaLotes ?? true),
      createLoteIngreso: jest.fn(async () => ({ id: `lote-${++n}` })),
      generarNumeroLote: (...args: any[]) => (LotesService.prototype.generarNumeroLote as any).apply({}, args),
      bloquearStockDe: jest.fn(async () => undefined),
    };
    const contabilidad: any = { tieneModuloContabilidad: jest.fn().mockResolvedValue(false) };
    const service = new ImportacionesService(prisma, {} as any, {} as any, contabilidad, {} as any, lotesService, {} as any);
    const liberar = (lotes?: any[]) => service.liberarEmbarque('emb-1', { deposito_destino_id: 'dep-1', lotes } as any, 'emp-1', 'u-1');
    return { tx, lotesService, liberar };
  };

  it('sin número crea el lote LYYYYMMDD-NNN con el costo prorrateado y el movimiento lleva lote_id', async () => {
    const { tx, lotesService, liberar } = crear({ prefijos: ['L20990101-004'] });
    const res = await liberar();

    expect(lotesService.createLoteIngreso).toHaveBeenCalledTimes(1);
    const params = lotesService.createLoteIngreso.mock.calls[0][1];
    expect(params).toEqual(expect.objectContaining({ productoId: 'p1', depositoId: 'dep-1', cantidad: 10, costoUnitario: 1500, fechaVencimiento: null }));
    expect(params.numeroLote).toMatch(/^L\d{8}-\d{3}$/);

    const movs = tx.movimientos_inventario.create.mock.calls.map((c: any) => c[0].data);
    expect(movs.find((m: any) => m.producto_id === 'p1')).toEqual(expect.objectContaining({ lote_id: 'lote-1', documento_origen: 'IMP', cantidad: 10 }));
    // el producto sin lotes entra sin lote, como antes
    expect(movs.find((m: any) => m.producto_id === 'p2').lote_id).toBeNull();
    // el ítem guarda qué lote creó, para revertir
    expect(tx.imp_embarque_items.update).toHaveBeenCalledWith({ where: { id: 'it-1' }, data: expect.objectContaining({ lote_id: 'lote-1', estado: 'DISPONIBLE' }) });
    expect(res.lotes_creados).toBe(1);
  });

  it('con número y fechas usa lo que cargó el usuario', async () => {
    const { lotesService, liberar } = crear();
    await liberar([{ item_id: 'it-1', numero_lote: ' A-77 ', fecha_fabricacion: '2026-10-01', fecha_vencimiento: '2027-03-31' }]);
    expect(lotesService.createLoteIngreso.mock.calls[0][1]).toEqual(
      expect.objectContaining({ numeroLote: 'A-77', fechaFabricacion: new Date('2026-10-01T00:00:00.000Z'), fechaVencimiento: new Date('2027-03-31T00:00:00.000Z') }),
    );
  });

  it('rechaza un número de lote que el producto ya tiene', async () => {
    const { tx, liberar } = crear({ existente: { id: 'x', productos: { descripcion: 'Aceite 1L' } } });
    await expect(liberar([{ item_id: 'it-1', numero_lote: 'A-77' }])).rejects.toMatchObject({
      response: { codigo: 'LOTE_DUPLICADO', linea: 1, message: expect.stringMatching(/Aceite 1L ya tiene un lote A-77/) },
    });
    expect(tx.imp_embarques.update).not.toHaveBeenCalled();
  });

  it('rechaza vencimiento anterior a la fabricación', async () => {
    const { liberar } = crear();
    await expect(liberar([{ item_id: 'it-1', fecha_fabricacion: '2026-10-01', fecha_vencimiento: '2026-09-01' }])).rejects.toMatchObject({
      response: { codigo: 'LOTE_VENCE_ANTES', linea: 1, message: expect.stringMatching(/vence antes de su fecha de fabricación/) },
    });
  });

  it('rechaza datos de lote de un ítem ajeno al embarque', async () => {
    const { liberar } = crear();
    await expect(liberar([{ item_id: 'otro' }])).rejects.toMatchObject({ response: { codigo: 'DATOS_CAMBIADOS' } });
  });

  it('si la sucursal no usa lotes, no crea lote', async () => {
    const { tx, lotesService, liberar } = crear({ usaLotes: false });
    await liberar([{ item_id: 'it-1', numero_lote: 'A-77' }]);
    expect(lotesService.createLoteIngreso).not.toHaveBeenCalled();
    expect(tx.movimientos_inventario.create.mock.calls.every((c: any) => c[0].data.lote_id === null)).toBe(true);
  });
});
