import { BadRequestException, ValidationPipe } from '@nestjs/common';
import { crearIntegracionMock } from 'src/contabilidad/services/__helpers__/integracion-mock';
import { CODIGO_PERIODO_NO_ABIERTO } from 'src/contabilidad/services/asientos.service';
import { solicitudInvalida } from 'src/common/utils/error-estructurado';
import { CerrarEmbarqueDto, ReabrirEmbarqueDto } from './dto/importaciones.dto';
import { ImportacionesBitacoraPresenter } from './services/importaciones-bitacora.presenter';
import { ImportacionesService } from './services/importaciones.service';

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

/**
 * Cerrar con fecha, reabrir con reversa, sellar y el asiento complementario de un costo tardío (plan Task 12; spec D5,
 * B18, filas 8–9 de la matriz; preflight F1, F4, F6, F8, F9).
 *
 * Un solo «mundo» con estado: el mismo Prisma de mentira lo usan ImportacionesService y el ContabilidadIntegracionService
 * real (`crearIntegracionMock`). Cada concepto mapeado resuelve a `cta-<CONCEPTO>`; el pasivo de cada proveedor, a
 * `cta-PAS-<proveedor>`. El saldo de la cuenta puente sale de los documentos vigentes (campo `puente` de cada uno, más
 * las líneas a la puente de los asientos que se crean).
 */

const EMPRESA = 'emp';
const PUENTE = 'cta-IMPORTACIONES_EN_CURSO';
/** «Hoy» de las pruebas: 25/10/2026 a media mañana de Paraguay. */
const AHORA = new Date('2026-10-25T13:00:00.000Z');
/** La liberación fue el 20/10 (bitácora). */
const LIBERADO_EL = new Date('2026-10-20T15:00:00.000Z');

const CONCEPTOS: Record<string, { id: string; codigo: string; nombre: string; afecta_costo: boolean }> = {
  'con-FOB': { id: 'con-FOB', codigo: 'FOB', nombre: 'FOB', afecta_costo: true },
  'con-FLE': { id: 'con-FLE', codigo: 'FLETE_INTERNO', nombre: 'Flete interno', afecta_costo: true },
};

interface Opciones {
  estado?: string;
  embarque?: Record<string, unknown>;
  faltan?: string[];
  sinPeriodo?: boolean;
  contabilidad?: boolean;
  documentos?: Array<Record<string, any>>;
  componentes?: Array<Record<string, any>>;
  asientosManuales?: Array<Record<string, any>>;
  despacho?: Record<string, unknown>;
}

function mundo(opts: Opciones = {}) {
  const estado = {
    embarque: {
      id: 'emb-1',
      empresa_id: EMPRESA,
      numero: 'IMP-2026-000001',
      estado: opts.estado ?? 'LIBERADO',
      activo: true,
      perfil: 'AUTOS',
      proveedor_id: 'p-zhang',
      moneda_id: 'mon-pyg',
      moneda: { id: 'mon-pyg', codigo: 'PYG' },
      usuario_id: 'u-1',
      fecha_cierre: null,
      asiento_cierre_estado: null,
      asiento_cierre_codigo: null,
      asiento_cierre_mensaje: null,
      updated_at: new Date('2026-10-20T15:00:00.000Z'),
      ...opts.embarque,
    } as Record<string, any>,
    despacho: {
      id: 'des-1',
      empresa_id: EMPRESA,
      embarque_id: 'emb-1',
      numero_despacho: '26032IC04008192T',
      fecha_despacho: new Date('2026-10-10T00:00:00.000Z'),
      despachante_id: 'p-desp',
      arancel_gs: 0,
      iva_importacion_gs: 0,
      iva_importacion_5_gs: 0,
      isc_gs: 0,
      inc_gs: 0,
      anticipo_ire_gs: 0,
      tasa_ana_gs: 0,
      otros_gs: 0,
      total_tributos_gs: 0,
      estado: 'CONFIRMADO',
      confirmado_at: new Date('2026-10-10T12:00:00.000Z'),
      usuario_id: 'u-1',
      asiento_estado: 'GENERADO',
      asiento_codigo: null,
      asiento_mensaje: null,
      ...opts.despacho,
    } as Record<string, any>,
    componentes: (opts.componentes ?? [{ id: 'c-fob', concepto_id: 'con-FOB', importe_gs: 1_000_000 }]).map((c, i) => ({
      empresa_id: EMPRESA,
      embarque_id: 'emb-1',
      activo: true,
      proveedor_id: null,
      compra_id: null,
      gasto_id: null,
      cuenta_pagar_id: null,
      asentado_documento_id: null,
      asiento_estado: null,
      asiento_codigo: null,
      asiento_mensaje: null,
      fecha_devengo: null,
      descripcion: c.id,
      created_at: new Date(Date.UTC(2026, 9, 1, 0, i)),
      concepto: CONCEPTOS[c.concepto_id],
      ...c,
    })) as Array<Record<string, any>>,
    bitacora: [{ embarque_id: 'emb-1', empresa_id: EMPRESA, evento: 'ESTADO_CAMBIO', estado_anterior: 'DESPACHADO', estado_nuevo: 'LIBERADO', created_at: LIBERADO_EL }] as Array<
      Record<string, any>
    >,
    // El despacho ya asentado dejó 1.000.000 en la puente.
    documentos: opts.documentos ?? [
      {
        id: 'doc-des',
        empresa_id: EMPRESA,
        tipo: 'DESPACHO_IMPORTACION',
        origen_tipo: 'imp_despacho',
        origen_id: 'des-1',
        estado: 'CONFIRMADO',
        puente: 1_000_000,
        asiento: { numero: 10 },
      },
    ],
    asientos: [] as Array<{ documento_id: string; fecha: string; glosa: string; lineas: any[] }>,
  };

  const coincide = (fila: Record<string, any>, where: Record<string, any> = {}) =>
    Object.entries(where).every(([k, v]) => {
      if (k === 'OR' || k === 'AND' || k === 'NOT') return true;
      if (v && typeof v === 'object' && 'in' in v) return (v.in as unknown[]).includes(fila[k]);
      if (v && typeof v === 'object') return true;
      return fila[k] === v;
    });
  const conAsiento = (d: Record<string, any>) => ({ ...d, asiento: d.asiento ? { id: `as-${d.id}`, ...d.asiento } : null });
  const docDeAsiento = (asientoId: string) => estado.documentos.find((d) => `as-${d.id}` === asientoId);
  const puenteDe = (d: Record<string, any>) => Number(d.puente ?? 0);

  const tablas: any = {
    $executeRaw: jest.fn().mockResolvedValue(undefined),
    imp_config_empresa: { findUnique: jest.fn().mockResolvedValue({ empresa_id: EMPRESA, modulo_operativo_activo: true, perfil_activo: 'AUTOS' }) },
    empresa_monedas: { findFirst: jest.fn().mockResolvedValue({ moneda_id: 'mon-pyg' }) },
    moneda: { findUnique: jest.fn().mockResolvedValue({ id: 'mon-pyg', codigo: 'PYG' }), findFirst: jest.fn().mockResolvedValue({ id: 'mon-pyg' }) },
    imp_embarques: {
      findFirst: jest.fn().mockImplementation(() => Promise.resolve({ ...estado.embarque })),
      findUnique: jest.fn().mockImplementation(() => Promise.resolve({ ...estado.embarque, despacho: { ...estado.despacho } })),
      update: jest.fn().mockImplementation(({ data }: any) => Promise.resolve(Object.assign(estado.embarque, data))),
    },
    imp_embarques_bitacora: {
      create: jest.fn().mockImplementation(({ data }: any) => Promise.resolve(estado.bitacora.push({ ...data, created_at: new Date() }))),
      findFirst: jest.fn().mockImplementation(({ where }: any) => {
        const ok = (b: Record<string, any>) =>
          b.embarque_id === where.embarque_id && (where.OR ?? []).some((o: Record<string, any>) => Object.entries(o).every(([k, v]) => b[k] === v));
        const filas = estado.bitacora.filter(ok).sort((a, b) => b.created_at.getTime() - a.created_at.getTime());
        return Promise.resolve(filas[0] ?? null);
      }),
    },
    imp_despachos: {
      findFirst: jest.fn().mockImplementation(() => Promise.resolve({ ...estado.despacho })),
      findUnique: jest.fn().mockImplementation(() => Promise.resolve({ ...estado.despacho, embarque: { ...estado.embarque } })),
      findMany: jest.fn().mockImplementation(() => Promise.resolve([{ id: estado.despacho.id }])),
      update: jest.fn().mockImplementation(({ data }: any) => Promise.resolve(Object.assign(estado.despacho, data))),
    },
    imp_conceptos_costo: {
      findFirst: jest.fn().mockImplementation(({ where }: any) => Promise.resolve(CONCEPTOS[where.id] ?? null)),
      findUnique: jest.fn().mockImplementation(({ where }: any) => Promise.resolve(CONCEPTOS[where.id] ?? null)),
      findMany: jest.fn().mockResolvedValue([]),
    },
    imp_componentes_costo: {
      findMany: jest
        .fn()
        .mockImplementation(({ where }: any = {}) =>
          Promise.resolve(estado.componentes.filter((c) => c.activo && (!where?.embarque_id || c.embarque_id === where.embarque_id)).map((c) => ({ ...c }))),
        ),
      findFirst: jest.fn().mockImplementation(({ where }: any) => Promise.resolve(estado.componentes.find((c) => c.activo && coincide(c, where)) ?? null)),
      findUnique: jest.fn().mockImplementation(({ where }: any) => {
        const c = estado.componentes.find((x) => x.id === where.id);
        return Promise.resolve(c ? { ...c, embarque: { ...estado.embarque } } : null);
      }),
      create: jest.fn().mockImplementation(({ data }: any) => {
        const fila = {
          id: `c-nuevo-${estado.componentes.length + 1}`,
          activo: true,
          compra_id: null,
          gasto_id: null,
          cuenta_pagar_id: null,
          asentado_documento_id: null,
          asiento_estado: null,
          asiento_codigo: null,
          asiento_mensaje: null,
          created_at: new Date(),
          concepto: CONCEPTOS[data.concepto_id],
          ...data,
        };
        estado.componentes.push(fila);
        return Promise.resolve(fila);
      }),
      update: jest.fn().mockImplementation(({ where, data }: any) => Promise.resolve(Object.assign(estado.componentes.find((c) => c.id === where.id) ?? {}, data))),
      updateMany: jest.fn().mockImplementation(({ where, data }: any) => {
        const filas = estado.componentes.filter((c) => (where.id?.in ?? [where.id]).includes(c.id));
        filas.forEach((c) => Object.assign(c, data));
        return Promise.resolve({ count: filas.length });
      }),
    },
    proveedores: {
      findFirst: jest.fn().mockResolvedValue({ id: 'p-flete', tipo_entidad: 'PROVEEDOR' }),
      findMany: jest.fn().mockImplementation(({ where }: any) => Promise.resolve((where.id.in as string[]).map((id) => ({ id, personas: { razon_social: id.toUpperCase() } })))),
    },
    tes_movimientos: { findMany: jest.fn().mockResolvedValue([]), findFirst: jest.fn().mockResolvedValue(null) },
    nota_credito_compra_cab: { findMany: jest.fn().mockResolvedValue([]) },
    cont_documentos: {
      findFirst: jest.fn().mockImplementation(({ where }: any) => {
        const d = estado.documentos.find((x) => coincide(x, where));
        return Promise.resolve(d ? conAsiento(d) : null);
      }),
      findMany: jest.fn().mockImplementation(({ where }: any) => {
        // saldoPuenteDeImportacion pide con OR por origen; correccionesManuales, por origen_tipo y estado.
        const porOrigen = (d: Record<string, any>) => !where.OR || where.OR.some((o: any) => o.origen_tipo === d.origen_tipo && o.origen_id.in.includes(d.origen_id));
        return Promise.resolve(estado.documentos.filter((d) => d.empresa_id === where.empresa_id && coincide(d, where) && porOrigen(d)).map(conAsiento));
      }),
      create: jest.fn().mockImplementation(({ data }: any) => {
        const doc = { id: `doc-${estado.documentos.length + 1}`, ...data };
        estado.documentos.push(doc);
        return Promise.resolve(doc);
      }),
      update: jest.fn().mockImplementation(({ where, data }: any) => Promise.resolve(Object.assign(estado.documentos.find((d) => d.id === where.id) ?? {}, data))),
    },
    cont_asientos: {
      findMany: jest.fn().mockImplementation(({ where }: any) => {
        if (where?.documento_id === null) return Promise.resolve(opts.asientosManuales ?? []);
        const docs = estado.documentos.filter(
          (d) =>
            where?.documento_id?.in?.includes(d.id) &&
            (!where.estado || d.estado === where.estado) &&
            (!where.documento || (d.origen_tipo === where.documento.origen_tipo && d.estado === where.documento.estado)),
        );
        return Promise.resolve(docs.map((d) => ({ id: `as-${d.id}`, documento_id: d.id })));
      }),
    },
    cont_asientos_det: {
      aggregate: jest.fn().mockImplementation(({ where }: any) => {
        const docs = (where.asiento_id.in as string[]).map(docDeAsiento).filter(Boolean);
        const saldo = docs.reduce((s, d) => s + puenteDe(d), 0);
        return Promise.resolve({ _sum: { debe_pyg: Math.max(saldo, 0), haber_pyg: Math.max(-saldo, 0) } });
      }),
    },
  };

  const integracion = crearIntegracionMock(tablas, opts.faltan ?? []);
  integracion.tieneModuloContabilidad.mockResolvedValue(opts.contabilidad ?? true);
  integracion.resolverCuentaPasivo = jest.fn().mockImplementation((id: string) => Promise.resolve(`cta-PAS-${id}`));
  integracion.asientos.crearConfirmado.mockImplementation((_e: string, _u: string, documentoId: string, datos: any) => {
    const lineas = datos.lineas as Array<{ cuenta_id: string; debe_moneda: number; haber_moneda: number }>;
    const doc = estado.documentos.find((d) => d.id === documentoId);
    const numero = 100 + estado.asientos.length;
    if (doc) {
      doc.puente = lineas.filter((l) => l.cuenta_id === PUENTE).reduce((s, l) => s + l.debe_moneda - l.haber_moneda, 0);
      doc.asiento = { numero, glosa: datos.glosa, updated_at: new Date() };
    }
    estado.asientos.push({ documento_id: documentoId, fecha: datos.fecha, glosa: datos.glosa, lineas });
    return Promise.resolve({ id: `as-${documentoId}`, numero });
  });
  integracion.asientos.revertir = jest.fn().mockImplementation((asientoId: string) => {
    const doc = docDeAsiento(asientoId);
    if (doc) {
      doc.estado = 'REVERTIDO';
      doc.asiento = { ...doc.asiento, updated_at: new Date() };
    }
    return Promise.resolve(undefined);
  });
  if (opts.sinPeriodo) {
    integracion.periodos.resolverPeriodoPorFecha.mockRejectedValue(new BadRequestException('No existe un período contable abierto para la fecha 2026-10-22'));
  }
  const prisma = integracion.prisma;
  const costeo = { recalcular: jest.fn().mockResolvedValue(undefined) };
  const service = new ImportacionesService(prisma, costeo as any, {} as any, integracion, {} as any, {} as any, {} as any);
  // La respuesta del detalle (Task 15) no es lo que se prueba acá.
  jest.spyOn(service, 'findOne').mockResolvedValue({ id: 'emb-1' } as any);
  return { service, integracion, prisma, estado };
}

const cuerpo = async (promesa: Promise<unknown>) => {
  try {
    await promesa;
  } catch (e: any) {
    return { status: e.getStatus?.(), ...e.getResponse() };
  }
  throw new Error('No lanzó');
};

const eventos = (estado: any) => estado.bitacora.map((b: any) => b.evento);
const cerrar = (s: ImportacionesService, fecha = '2026-10-22') => s.cerrar('emb-1', { fecha_cierre: fecha }, EMPRESA, 'u-1');
const reabrir = (s: ImportacionesService, motivo = 'Falta la factura del flete') => s.reabrir('emb-1', { motivo }, EMPRESA, 'u-1');
const lineasDe = (a: { lineas: any[] }) => a.lineas.map((l) => [l.cuenta_id, l.debe_moneda, l.haber_moneda]);

beforeAll(() => {
  jest.useFakeTimers({ now: AHORA, doNotFake: ['nextTick', 'setImmediate', 'queueMicrotask', 'setTimeout', 'setInterval', 'clearTimeout', 'clearInterval'] });
});
afterAll(() => jest.useRealTimers());

describe('Importaciones — cerrar el expediente', () => {
  it('cerrar con fecha de mañana o antes de liberar → FECHA_CIERRE_INVALIDA', async () => {
    const { service, estado, integracion } = mundo();
    expect(await cuerpo(cerrar(service, '2026-10-26'))).toMatchObject({ status: 400, codigo: 'FECHA_CIERRE_INVALIDA', campo: 'fecha_cierre' });
    expect(await cuerpo(cerrar(service, '2026-10-19'))).toMatchObject({ status: 400, codigo: 'FECHA_CIERRE_INVALIDA', campo: 'fecha_cierre' });
    expect(estado.embarque.estado).toBe('LIBERADO');
    expect(integracion.asientos.crearConfirmado).not.toHaveBeenCalled();
    // El día de la liberación y hoy valen.
    await expect(mundo().service.cerrar('emb-1', { fecha_cierre: '2026-10-20' }, EMPRESA, 'u-1')).resolves.toMatchObject({ embarque_estado: 'CERRADO' });
    await expect(mundo().service.cerrar('emb-1', { fecha_cierre: '2026-10-25' }, EMPRESA, 'u-1')).resolves.toMatchObject({ embarque_estado: 'CERRADO' });
  });

  it('el asiento de cierre va con fecha_cierre (D5) y descarga la puente', async () => {
    const { service, estado, integracion } = mundo();
    const res = await cerrar(service);
    expect(res).toEqual({ embarque_estado: 'CERRADO', asiento: { estado: 'GENERADO', documento_id: 'doc-2', numero: '100' } });
    expect(estado.asientos).toHaveLength(1);
    expect(estado.asientos[0].fecha).toBe('2026-10-22');
    expect(integracion.periodos.resolverPeriodoPorFecha).toHaveBeenCalledWith(EMPRESA, new Date('2026-10-22T00:00:00.000Z'));
    expect(lineasDe(estado.asientos[0])).toEqual([
      ['cta-INVENTARIO', 1_000_000, 0],
      [PUENTE, 0, 1_000_000],
    ]);
    expect(estado.embarque).toMatchObject({
      estado: 'CERRADO',
      fecha_cierre: new Date('2026-10-22T00:00:00.000Z'),
      asiento_cierre_estado: 'GENERADO',
      asiento_cierre_codigo: null,
    });
    expect(eventos(estado)).toEqual(expect.arrayContaining(['ESTADO_CAMBIO', 'EXPEDIENTE_CERRADO']));
    expect(estado.bitacora.find((b) => b.evento === 'EXPEDIENTE_CERRADO')?.detalle).toMatchObject({ fecha_cierre: '2026-10-22' });
  });

  it('cerrar un embarque que no está LIBERADO → ESTADO_CAMBIADO con estado_actual', async () => {
    const { service } = mundo({ estado: 'DESPACHADO' });
    expect(await cuerpo(cerrar(service))).toMatchObject({ status: 409, codigo: 'ESTADO_CAMBIADO', estado_actual: 'DESPACHADO', estado_pedido: 'CERRADO' });
  });

  it('sin puente → NO_APLICA y sellar no lo exige (fila 8)', async () => {
    const { service, estado, integracion } = mundo({ faltan: ['IMPORTACIONES_EN_CURSO'] });
    const res = await cerrar(service);
    expect(res.asiento).toEqual({ estado: 'NO_APLICA' });
    expect(integracion.asientos.crearConfirmado).not.toHaveBeenCalled();
    expect(estado.embarque.asiento_cierre_estado).toBe('NO_APLICA');
    expect(eventos(estado)).not.toContain('ASIENTO_FALLIDO');
    await expect(service.sellar('emb-1', EMPRESA, 'u-1')).resolves.toMatchObject({ embarque_estado: 'SELLADO' });
    expect(eventos(estado)).toContain('EXPEDIENTE_SELLADO');
  });

  it('sin Contabilidad → NO_APLICA y sellar no lo exige', async () => {
    const { service, estado } = mundo({ contabilidad: false });
    expect((await cerrar(service)).asiento).toEqual({ estado: 'NO_APLICA' });
    await service.sellar('emb-1', EMPRESA, 'u-1');
    expect(estado.embarque.estado).toBe('SELLADO');
  });

  it('sin período: el cierre queda CERRADO con el asiento PENDIENTE/PERIODO_CERRADO, ASIENTO_FALLIDO, y el reintento lo genera', async () => {
    const { service, estado, integracion } = mundo({ sinPeriodo: true });
    const res = await cerrar(service);
    expect(res).toEqual({ embarque_estado: 'CERRADO', asiento: { estado: 'PENDIENTE', codigo: 'PERIODO_CERRADO', mensaje: expect.stringContaining('2026-10-22') } });
    expect(estado.embarque).toMatchObject({ estado: 'CERRADO', asiento_cierre_estado: 'PENDIENTE', asiento_cierre_codigo: 'PERIODO_CERRADO' });
    expect(estado.bitacora.find((b) => b.evento === 'ASIENTO_FALLIDO')?.detalle).toMatchObject({ asiento: 'CIERRE', codigo: 'PERIODO_CERRADO' });

    integracion.periodos.resolverPeriodoPorFecha.mockResolvedValue('p');
    const reintento = await service.reintegrarCierre('emb-1', EMPRESA, 'u-1');
    expect(reintento).toEqual({ embarque_estado: 'CERRADO', asiento: { estado: 'GENERADO', documento_id: 'doc-2', numero: '100' } });
    expect(estado.asientos[0].fecha).toBe('2026-10-22');
    expect(estado.embarque).toMatchObject({ asiento_cierre_estado: 'GENERADO', asiento_cierre_codigo: null, asiento_cierre_mensaje: null });
    expect(eventos(estado)).toContain('ASIENTO_REINTENTADO');
  });

  it('el error del asiento después del commit no rompe la respuesta: queda guardado con ASIENTO_FALLIDO', async () => {
    const { service, estado, integracion } = mundo();
    integracion.asientos.crearConfirmado.mockRejectedValue(new Error('La cuenta 1.1.4 está inactiva'));
    const res = await cerrar(service);
    expect(res.asiento).toEqual({ estado: 'PENDIENTE', codigo: 'ASIENTO_ERROR', mensaje: 'La cuenta 1.1.4 está inactiva' });
    expect(estado.embarque).toMatchObject({ estado: 'CERRADO', asiento_cierre_estado: 'PENDIENTE', asiento_cierre_codigo: 'ASIENTO_ERROR' });
    expect(eventos(estado)).toContain('ASIENTO_FALLIDO');
  });
});

describe('Importaciones — reintentar el asiento de cierre', () => {
  it('con uno CONFIRMADO → ASIENTO_YA_GENERADO con su número y el estado al día', async () => {
    const documentos = [{ id: 'doc-c', empresa_id: EMPRESA, origen_tipo: 'imp_cierre', origen_id: 'emb-1', estado: 'CONFIRMADO', asiento: { numero: 33 } }];
    const { service, estado, integracion } = mundo({ estado: 'CERRADO', embarque: { fecha_cierre: new Date('2026-10-22T00:00:00.000Z') }, documentos });
    expect(await cuerpo(service.reintegrarCierre('emb-1', EMPRESA, 'u-1'))).toMatchObject({ status: 409, codigo: 'ASIENTO_YA_GENERADO', numero: '33' });
    expect(integracion.asientos.crearConfirmado).not.toHaveBeenCalled();
    expect(estado.embarque.asiento_cierre_estado).toBe('GENERADO');
  });

  it('con la corrección manual del revertido → ASIENTO_YA_GENERADO CORRECCION_MANUAL sin generar otro (F1)', async () => {
    const glosa = 'Cierre importación IMP-2026-000001';
    const documentos = [
      {
        id: 'doc-c',
        empresa_id: EMPRESA,
        origen_tipo: 'imp_cierre',
        origen_id: 'emb-1',
        estado: 'REVERTIDO',
        asiento: { numero: 33, glosa, updated_at: new Date('2026-10-23T00:00:00Z') },
      },
    ];
    const asientosManuales = [{ id: 'as-man', numero: 77, glosa: `CORRECCIÓN: ${glosa}`, created_at: new Date('2026-10-24T00:00:00Z') }];
    const { service, estado, integracion } = mundo({ estado: 'CERRADO', embarque: { fecha_cierre: new Date('2026-10-22T00:00:00.000Z') }, documentos, asientosManuales });
    const e = await cuerpo(service.reintegrarCierre('emb-1', EMPRESA, 'u-1'));
    expect(e).toMatchObject({ status: 409, codigo: 'ASIENTO_YA_GENERADO', numero: '77', motivo: 'CORRECCION_MANUAL' });
    expect(integracion.asientos.crearConfirmado).not.toHaveBeenCalled();
    expect(estado.embarque).toMatchObject({ asiento_cierre_estado: 'GENERADO', asiento_cierre_codigo: 'CORRECCION_MANUAL' });
  });

  it('SELLADO legado sin fecha_cierre: el reintento y el integrador responden FECHA_CIERRE_REQUERIDA, nunca usan hoy', async () => {
    const { service, integracion } = mundo({ estado: 'SELLADO' });
    expect(await cuerpo(service.reintegrarCierre('emb-1', EMPRESA, 'u-1'))).toMatchObject({ status: 409, codigo: 'FECHA_CIERRE_REQUERIDA' });
    await expect(integracion.integrarCierreImportacion('emb-1')).rejects.toMatchObject({ response: expect.objectContaining({ codigo: 'FECHA_CIERRE_REQUERIDA' }) });
    expect(integracion.asientos.crearConfirmado).not.toHaveBeenCalled();
  });

  it('un embarque LIBERADO no reintenta el cierre: ESTADO_CAMBIADO', async () => {
    const { service } = mundo();
    expect(await cuerpo(service.reintegrarCierre('emb-1', EMPRESA, 'u-1'))).toMatchObject({ status: 409, codigo: 'ESTADO_CAMBIADO', estado_actual: 'LIBERADO' });
  });
});

describe('Importaciones — reabrir el expediente', () => {
  it('reabrir revierte el asiento en la misma tx y al volver a cerrar se genera otro (fila 9, B18)', async () => {
    const { service, estado, integracion, prisma } = mundo();
    await cerrar(service);
    expect(estado.documentos.find((d) => d.id === 'doc-2')).toMatchObject({ origen_tipo: 'imp_cierre', estado: 'CONFIRMADO' });

    const res = await reabrir(service);
    expect(res).toMatchObject({ embarque_estado: 'LIBERADO', asiento_revertido: true });
    expect(integracion.asientos.revertir).toHaveBeenCalledWith('as-doc-2', EMPRESA, 'u-1', expect.anything());
    // La reversión corre con el cliente de la transacción de la reapertura.
    const txUsada = integracion.asientos.revertir.mock.calls[0][3];
    expect(txUsada).toBe(prisma);
    expect(prisma.$transaction).toHaveBeenCalled();
    expect(estado.embarque).toMatchObject({ estado: 'LIBERADO', fecha_cierre: null, asiento_cierre_estado: null, asiento_cierre_codigo: null, asiento_cierre_mensaje: null });
    const reabierto = estado.bitacora.find((b) => b.evento === 'EXPEDIENTE_REABIERTO');
    expect(reabierto?.observacion).toBe('Falta la factura del flete');

    const otra = await cerrar(service, '2026-10-24');
    expect(otra.asiento).toMatchObject({ estado: 'GENERADO', documento_id: 'doc-3' });
    expect(estado.asientos).toHaveLength(2);
    expect(estado.asientos[1].fecha).toBe('2026-10-24');
    // El revertido se desvincula para que el nuevo ocupe el origen (único empresa/origen).
    expect(estado.documentos.find((d) => d.id === 'doc-2')).toMatchObject({ estado: 'REVERTIDO', origen_tipo: null, origen_id: null });
  });

  it('reabrir con la reversión que lanza deja CERRADO y propaga el código (Review Focus, F8)', async () => {
    const documentos = [
      { id: 'doc-des', empresa_id: EMPRESA, origen_tipo: 'imp_despacho', origen_id: 'des-1', estado: 'CONFIRMADO', puente: 1_000_000, asiento: { numero: 10 } },
      { id: 'doc-c', empresa_id: EMPRESA, origen_tipo: 'imp_cierre', origen_id: 'emb-1', estado: 'CONFIRMADO', asiento: { numero: 33 } },
    ];
    const { service, estado, integracion } = mundo({
      estado: 'CERRADO',
      embarque: { fecha_cierre: new Date('2026-10-22T00:00:00.000Z'), asiento_cierre_estado: 'GENERADO' },
      documentos,
    });
    integracion.asientos.revertir.mockRejectedValue(
      solicitudInvalida({ message: 'No se puede revertir: el período 10/2026 del asiento está CERRADO.', codigo: CODIGO_PERIODO_NO_ABIERTO }),
    );
    const e = await cuerpo(reabrir(service));
    expect(e).toMatchObject({ status: 409, codigo: 'PERIODO_CERRADO' });
    expect(e.message).toContain('22/10/2026');
    expect(estado.embarque).toMatchObject({ estado: 'CERRADO', asiento_cierre_estado: 'GENERADO' });
    expect(eventos(estado)).not.toContain('EXPEDIENTE_REABIERTO');
    expect(estado.documentos.find((d) => d.id === 'doc-c')?.estado).toBe('CONFIRMADO');
  });

  it('otro error de la reversión se propaga tal cual', async () => {
    const documentos = [{ id: 'doc-c', empresa_id: EMPRESA, origen_tipo: 'imp_cierre', origen_id: 'emb-1', estado: 'CONFIRMADO', asiento: { numero: 33 } }];
    const { service, estado, integracion } = mundo({ estado: 'CERRADO', embarque: { fecha_cierre: new Date('2026-10-22T00:00:00.000Z') }, documentos });
    integracion.asientos.revertir.mockRejectedValue(new Error('conexión caída'));
    await expect(reabrir(service)).rejects.toThrow('conexión caída');
    expect(estado.embarque.estado).toBe('CERRADO');
  });

  it('reabrir sin asiento de cierre (sin puente) reabre sin revertir nada', async () => {
    const { service, estado, integracion } = mundo({ estado: 'CERRADO', embarque: { fecha_cierre: new Date('2026-10-22T00:00:00.000Z'), asiento_cierre_estado: 'NO_APLICA' } });
    expect(await reabrir(service)).toMatchObject({ embarque_estado: 'LIBERADO', asiento_revertido: false });
    expect(integracion.asientos.revertir).not.toHaveBeenCalled();
    expect(estado.embarque.estado).toBe('LIBERADO');
  });

  it('reabrir sin motivo → 400 (DTO) y un embarque que no está CERRADO → ESTADO_CAMBIADO', async () => {
    const pipe = new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true });
    await expect(pipe.transform({}, { type: 'body', metatype: ReabrirEmbarqueDto })).rejects.toBeInstanceOf(BadRequestException);
    await expect(pipe.transform({ motivo: '' }, { type: 'body', metatype: ReabrirEmbarqueDto })).rejects.toBeInstanceOf(BadRequestException);
    await expect(pipe.transform({ motivo: 'x'.repeat(501) }, { type: 'body', metatype: ReabrirEmbarqueDto })).rejects.toBeInstanceOf(BadRequestException);
    await expect(pipe.transform({ motivo: 'Corrijo el flete' }, { type: 'body', metatype: ReabrirEmbarqueDto })).resolves.toEqual({ motivo: 'Corrijo el flete' });
    await expect(pipe.transform({}, { type: 'body', metatype: CerrarEmbarqueDto })).rejects.toBeInstanceOf(BadRequestException);
    await expect(pipe.transform({ fecha_cierre: '2026-10-22' }, { type: 'body', metatype: CerrarEmbarqueDto })).resolves.toEqual({ fecha_cierre: '2026-10-22' });

    const { service } = mundo();
    expect(await cuerpo(reabrir(service))).toMatchObject({ status: 409, codigo: 'ESTADO_CAMBIADO', estado_actual: 'LIBERADO', estado_pedido: 'LIBERADO' });
  });
});

describe('Importaciones — sellar el expediente', () => {
  it('sellar con asiento de cierre PENDIENTE → ASIENTO_CIERRE_PENDIENTE', async () => {
    const { service, estado } = mundo({ sinPeriodo: true });
    await cerrar(service);
    expect(await cuerpo(service.sellar('emb-1', EMPRESA, 'u-1'))).toMatchObject({ status: 409, codigo: 'ASIENTO_CIERRE_PENDIENTE' });
    expect(estado.embarque.estado).toBe('CERRADO');
  });

  it('sellar con el asiento GENERADO pasa a SELLADO con su evento; un LIBERADO → ESTADO_CAMBIADO', async () => {
    const { service, estado } = mundo();
    await cerrar(service);
    expect(await service.sellar('emb-1', EMPRESA, 'u-1')).toEqual({ embarque_estado: 'SELLADO', asiento: { estado: 'GENERADO' } });
    expect(estado.embarque.estado).toBe('SELLADO');
    expect(estado.bitacora.filter((b) => b.evento === 'ESTADO_CAMBIO').at(-1)).toMatchObject({ estado_anterior: 'CERRADO', estado_nuevo: 'SELLADO' });
    expect(eventos(estado)).toContain('EXPEDIENTE_SELLADO');

    expect(await cuerpo(mundo().service.sellar('emb-1', EMPRESA, 'u-1'))).toMatchObject({ status: 409, codigo: 'ESTADO_CAMBIADO', estado_actual: 'LIBERADO' });
  });

  it('CERRADO legado sin estado guardado (NULL) con Contabilidad no se sella: hay que reintentar el cierre', async () => {
    const { service } = mundo({ estado: 'CERRADO', embarque: { fecha_cierre: new Date('2026-10-22T00:00:00.000Z') } });
    expect(await cuerpo(service.sellar('emb-1', EMPRESA, 'u-1'))).toMatchObject({ status: 409, codigo: 'ASIENTO_CIERRE_PENDIENTE' });
  });
});

describe('Importaciones — asiento complementario de un costo tardío', () => {
  const flete = {
    concepto_id: 'con-FLE',
    proveedor_id: 'p-flete',
    importe: 300_000,
    cotizacion: 1,
    criterio_prorrateo: 'FOB',
    fecha_devengo: '2026-10-12',
    descripcion: 'Flete a depósito',
  };

  it('costo manual en DESPACHADO con proveedor genera el complementario con fecha de devengo y su estado', async () => {
    const { service, estado } = mundo({ estado: 'DESPACHADO' });
    await service.addCosto('emb-1', flete as any, EMPRESA, 'u-1');
    const nuevo = estado.componentes.find((c) => c.descripcion === 'Flete a depósito');
    expect(estado.asientos).toHaveLength(1);
    expect(estado.asientos[0].fecha).toBe('2026-10-12');
    expect(lineasDe(estado.asientos[0])).toEqual([
      ['cta-IMPORTACION_TRIBUTOS', 300_000, 0],
      ['cta-PAS-p-flete', 0, 300_000],
    ]);
    const doc = estado.documentos.find((d) => d.origen_tipo === 'imp_componente');
    expect(doc).toMatchObject({ origen_id: nuevo.id, estado: 'CONFIRMADO' });
    expect(nuevo).toMatchObject({ asiento_estado: 'GENERADO', asiento_codigo: null, asentado_documento_id: doc.id });
  });

  it('sin fecha de devengo usa el día de alta en Paraguay', async () => {
    const { service, estado } = mundo({ estado: 'DESPACHADO' });
    jest.setSystemTime(new Date('2026-10-25T01:30:00.000Z')); // 24/10 a las 22:30 de Paraguay
    try {
      await service.addCosto('emb-1', { ...flete, fecha_devengo: undefined } as any, EMPRESA, 'u-1');
    } finally {
      jest.setSystemTime(AHORA);
    }
    expect(estado.asientos[0].fecha).toBe('2026-10-24');
  });

  it('el complementario fallido queda PENDIENTE con ASIENTO_FALLIDO y el reintento lo genera', async () => {
    const { service, estado, integracion } = mundo({ estado: 'DESPACHADO', sinPeriodo: true });
    await service.addCosto('emb-1', flete as any, EMPRESA, 'u-1');
    const nuevo = estado.componentes.find((c) => c.descripcion === 'Flete a depósito');
    expect(nuevo).toMatchObject({ asiento_estado: 'PENDIENTE', asiento_codigo: 'PERIODO_CERRADO', asentado_documento_id: null });
    expect(estado.bitacora.find((b) => b.evento === 'ASIENTO_FALLIDO')?.detalle).toMatchObject({ asiento: 'COSTO', componente_id: nuevo.id, codigo: 'PERIODO_CERRADO' });

    integracion.periodos.resolverPeriodoPorFecha.mockResolvedValue('p');
    const res = await service.reintegrarComponente('emb-1', nuevo.id, EMPRESA, 'u-1');
    expect(res.asiento).toMatchObject({ estado: 'GENERADO' });
    expect(nuevo).toMatchObject({ asiento_estado: 'GENERADO', asentado_documento_id: (res.asiento as any).documento_id });
    expect(eventos(estado)).toContain('ASIENTO_REINTENTADO');

    // Ya generado: el segundo reintento responde 409 sin otro asiento.
    expect(await cuerpo(service.reintegrarComponente('emb-1', nuevo.id, EMPRESA, 'u-1'))).toMatchObject({ status: 409, codigo: 'ASIENTO_YA_GENERADO' });
    expect(estado.asientos).toHaveLength(1);
  });

  it('un costo que entró al asiento del despacho no tiene complementario: el reintento lo dice', async () => {
    const { service } = mundo({ estado: 'DESPACHADO' });
    expect(await cuerpo(service.reintegrarComponente('emb-1', 'c-fob', EMPRESA, 'u-1'))).toMatchObject({ status: 409, codigo: 'ASIENTO_DESPACHO_PENDIENTE' });
  });

  it('antes de DESPACHADO un costo nuevo no genera complementario', async () => {
    const { service, estado } = mundo({ estado: 'EN_DESPACHO' });
    await service.addCosto('emb-1', flete as any, EMPRESA, 'u-1');
    expect(estado.asientos).toHaveLength(0);
    expect(estado.componentes.find((c) => c.descripcion === 'Flete a depósito')?.asiento_estado).toBeNull();
  });

  it('reintento del despacho con un costo tardío asentado por complementario no lo repite (F6)', async () => {
    const documentos = [
      {
        id: 'doc-des',
        empresa_id: EMPRESA,
        origen_tipo: 'imp_despacho',
        origen_id: 'des-1',
        estado: 'REVERTIDO',
        asiento: { numero: 10, glosa: 'Cierre despacho importación 26032IC04008192T (embarque IMP-2026-000001)', updated_at: new Date('2026-10-11T00:00:00Z') },
      },
    ];
    const { service, estado } = mundo({ estado: 'DESPACHADO', documentos, despacho: { asiento_estado: 'PENDIENTE', asiento_codigo: 'ASIENTO_REVERTIDO' } });
    await service.addCosto('emb-1', flete as any, EMPRESA, 'u-1');
    expect(estado.asientos).toHaveLength(1);

    await service.reintegrarContabilidadDespacho('emb-1', 'des-1', EMPRESA, 'u-1');
    expect(estado.asientos).toHaveLength(2);
    expect(lineasDe(estado.asientos[1])).toEqual([
      ['cta-IMPORTACION_TRIBUTOS', 1_000_000, 0],
      ['cta-PAS-p-zhang', 0, 1_000_000],
    ]);
    const nuevo = estado.componentes.find((c) => c.descripcion === 'Flete a depósito');
    expect(nuevo.asentado_documento_id).toBe(estado.asientos[0].documento_id);
  });

  it('el cierre suma a la puente lo que dejó el complementario (F4)', async () => {
    const documentos = [
      { id: 'doc-des', empresa_id: EMPRESA, origen_tipo: 'imp_despacho', origen_id: 'des-1', estado: 'CONFIRMADO', puente: 1_000_000, asiento: { numero: 10 } },
      { id: 'doc-comp', empresa_id: EMPRESA, origen_tipo: 'imp_componente', origen_id: 'c-tarde', estado: 'CONFIRMADO', puente: 300_000, asiento: { numero: 11 } },
    ];
    const componentes = [
      { id: 'c-fob', concepto_id: 'con-FOB', importe_gs: 1_000_000, asentado_documento_id: 'doc-des' },
      { id: 'c-tarde', concepto_id: 'con-FLE', proveedor_id: 'p-flete', importe_gs: 300_000, asentado_documento_id: 'doc-comp', asiento_estado: 'GENERADO' },
    ];
    const { service, estado } = mundo({ documentos, componentes });
    await cerrar(service);
    expect(lineasDe(estado.asientos[0])).toEqual([
      ['cta-INVENTARIO', 1_300_000, 0],
      [PUENTE, 0, 1_300_000],
    ]);
  });
});

describe('Importaciones — bitácora de los eventos nuevos', () => {
  it('el presenter nombra los eventos nuevos y el cambio de estado con las etiquetas', async () => {
    const prisma = {
      usuario: { findMany: jest.fn().mockResolvedValue([]) },
      proveedores: { findMany: jest.fn().mockResolvedValue([]) },
      moneda: { findMany: jest.fn().mockResolvedValue([]) },
      imp_conceptos_costo: { findMany: jest.fn().mockResolvedValue([]) },
      imp_embarque_items: { findMany: jest.fn().mockResolvedValue([]) },
      productos: { findMany: jest.fn().mockResolvedValue([]) },
      depositos: { findMany: jest.fn().mockResolvedValue([]) },
      cuentas_pagar: { findMany: jest.fn().mockResolvedValue([]) },
    };
    const presenter = new ImportacionesBitacoraPresenter(prisma as any);
    const base = { estado_anterior: null, estado_nuevo: null, observacion: null, usuario_id: null, created_at: AHORA, detalle: null };
    const r = await presenter.present(
      [
        { ...base, evento: 'EXPEDIENTE_CERRADO', detalle: { fecha_cierre: '2026-10-22' } },
        { ...base, evento: 'EXPEDIENTE_REABIERTO', observacion: 'Falta el flete' },
        { ...base, evento: 'EXPEDIENTE_SELLADO' },
        { ...base, evento: 'ASIENTO_FALLIDO', detalle: { asiento: 'CIERRE', estado: 'PENDIENTE', codigo: 'PERIODO_CERRADO' } },
        { ...base, evento: 'ASIENTO_REINTENTADO', detalle: { asiento: 'COSTO', estado: 'GENERADO', concepto: 'Flete interno' } },
        { ...base, evento: 'ASIENTO_FALLIDO', detalle: { numero_despacho: 'DSP-1', estado: 'PENDIENTE' } },
        { ...base, evento: 'ESTADO_CAMBIO', estado_anterior: 'LIBERADO', estado_nuevo: 'CERRADO' },
      ],
      EMPRESA,
      'emb-1',
    );
    expect(r.map((e) => e.resumen)).toEqual([
      'Se cerró el expediente',
      'Se reabrió el expediente',
      'Se selló el expediente',
      'El asiento contable del cierre quedó pendiente',
      'Se reintentó el asiento contable de un costo posterior al despacho: Flete interno',
      'El asiento contable del despacho quedó pendiente: DSP-1',
      'Cambió el estado del embarque: Liberado → Cerrado',
    ]);
    expect(r[0].datos).toContainEqual({ campo: 'Fecha de cierre', tipo: 'fecha', valor: '2026-10-22' });
    expect(r[1].observacion).toBe('Falta el flete');
  });
});
