import { Prisma } from '@prisma/client';
import { TesConciliacionService } from '../tes-conciliacion.service';

/**
 * Prisma, IA, integrador y categorías mockeados para `TesConciliacionService` (specs de S5). `$transaction` corre el callback con un
 * `tx` distinto del `prisma` y propaga lo que lance; `orden` anota cada llamada del `tx`, para afirmar la secuencia del bloqueo. Quien lo
 * usa mockea en su spec `module-access.util`, `submodulo.guard` y `ymdInAsuncion` (jest.mock va en el archivo del spec).
 */
export const EMP = '0e000000-0000-4000-8000-000000000001';
export const USER = 'u-1';
export const EXT = 'e0000000-0000-4000-8000-000000000001';
export const LIN = 'a0000000-0000-4000-8000-000000000001';
export const LIN2 = 'a0000000-0000-4000-8000-000000000002';
export const MOV = '30000000-0000-4000-8000-000000000001';
export const MOV2 = '30000000-0000-4000-8000-000000000002';
export const CTA = 'c7a00000-0000-4000-8000-000000000001';
export const CAT = 'ca700000-0000-4000-8000-000000000001';

const dec = (n: number) => new Prisma.Decimal(n);

export const linea = (o: Record<string, unknown> = {}) => ({
  id: LIN,
  extracto_id: EXT,
  fecha: new Date('2026-10-20T00:00:00.000Z'),
  descripcion: 'COMISION BANCO',
  referencia: 'R-1',
  debito: dec(1000),
  credito: dec(0),
  saldo: null,
  conciliado: false,
  sin_correspondencia: false,
  movimiento_id: null as string | null,
  created_at: new Date('2026-10-21T12:00:00.000Z'),
  movimiento: null as Record<string, unknown> | null,
  extracto: { cuenta_id: CTA, cuenta: { moneda: 'PYG', activo: true } },
  ...o,
});

export const movimiento = (o: Record<string, unknown> = {}) => ({
  id: MOV,
  empresa_id: EMP,
  cuenta_id: CTA,
  tipo: 'EGRESO',
  estado: 'CONFIRMADO',
  monto: dec(1000),
  origen_tipo: null as string | null,
  fecha: new Date('2026-10-20T00:00:00.000Z'),
  descripcion: 'Comisión',
  referencia: null,
  ...o,
});

export const extracto = (o: Record<string, unknown> = {}) => ({
  id: EXT,
  empresa_id: EMP,
  cuenta_id: CTA,
  periodo_desde: new Date('2026-10-01T00:00:00.000Z'),
  periodo_hasta: new Date('2026-10-31T00:00:00.000Z'),
  saldo_inicial: dec(100) as Prisma.Decimal | null,
  saldo_final: dec(200) as Prisma.Decimal | null,
  archivo_nombre: 'x.csv',
  estado: 'PENDIENTE',
  created_by: USER,
  created_at: new Date('2026-10-21T12:00:00.000Z'),
  updated_at: new Date('2026-10-21T12:00:00.000Z'),
  cuenta: { id: CTA, nombre: 'DOBA S.A.', moneda: 'PYG', activo: true, saldo_inicial: dec(0) },
  lineas: [] as Array<Record<string, unknown>>,
  ...o,
});

export interface Escenario {
  /** Lo que lee `tes_extracto_lineas.findFirst` antes de la transacción; `null` = no existe. */
  linea?: Record<string, unknown> | null;
  /** `tes_extracto_lineas.updateMany` en el `tx` (la guarda). */
  guarda?: number;
  /** Movimiento releído en el `tx`; `null` = ajeno, anulado o inexistente. */
  movimiento?: Record<string, unknown> | null;
  /** El `CONCILIACION_AJUSTE` confirmado y sin línea conciliada que encuentra Crear movimiento; por defecto, ninguno. */
  movimientoYaCreado?: Record<string, unknown> | null;
  /** Otra línea conciliada con el movimiento, leída en el `tx`. */
  otraLinea?: Record<string, unknown> | null;
  /** `$queryRaw` del `tx`: filas del `FOR UPDATE`. */
  bloqueo?: Array<{ id: string }>;
  categorias?: Array<Record<string, unknown>>;
  /** La cuenta releída bajo bloqueo en el `tx`; por defecto, la que trae la línea. */
  cuentaActivaEnTx?: boolean;
  extracto?: Record<string, unknown> | null;
  /** Para getExtractos. */
  extractos?: Array<Record<string, unknown>>;
  /** `findMany` de líneas fuera del `tx`. */
  lineas?: Array<Record<string, unknown>>;
  /** `count` de líneas `CONCILIACION_*` dentro del `tx`, al eliminar. */
  conConciliacion?: number;
  integrador?: jest.Mock;
  documentos?: Array<Record<string, unknown>>;
  documento?: Record<string, unknown> | null;
  grupos?: Array<Record<string, unknown>>;
  cuenta?: Record<string, unknown> | null;
  apiKey?: string | null;
  categoriasFindAll?: Array<Record<string, unknown>>;
  completar?: jest.Mock;
  movimientos?: Array<Record<string, unknown>>;
  constancia?: Record<string, unknown> | null;
}

export function armar(e: Escenario = {}) {
  const orden: string[] = [];
  const anotar = <T>(nombre: string, fn: () => T) =>
    jest.fn().mockImplementation(() => {
      orden.push(nombre);
      return Promise.resolve(fn());
    });
  const sqlDe = (strings: readonly string[]) => strings.join('?');
  const tx = {
    $queryRaw: jest.fn().mockImplementation((strings: readonly string[]) => {
      const sql = sqlDe(strings);
      if (sql.includes('tes_cuentas')) {
        orden.push('bloqueo-cuenta');
        const lineaLeida = (e.linea === undefined ? linea() : e.linea) as { extracto?: { cuenta?: { activo?: boolean } } } | null;
        return Promise.resolve([{ activo: e.cuentaActivaEnTx ?? lineaLeida?.extracto?.cuenta?.activo ?? true }]);
      }
      orden.push(sql.includes('tes_movimientos') ? 'bloqueo-movimiento' : 'bloqueo-extracto');
      return Promise.resolve(e.bloqueo ?? [{ id: EXT }]);
    }),
    tes_extracto_lineas: {
      updateMany: anotar('lineas.updateMany', () => ({ count: e.guarda ?? 1 })),
      update: anotar('lineas.update', () => ({})),
      findFirst: jest.fn().mockImplementation(({ where }: { where: { movimiento_id?: string; id?: string } }) => {
        if (where.movimiento_id) {
          orden.push('lineas.otra');
          return Promise.resolve(e.otraLinea ?? null);
        }
        return Promise.resolve(e.linea === undefined ? linea() : e.linea);
      }),
      findMany: anotar('lineas.findMany', () => [{ conciliado: true, sin_correspondencia: false }]),
      createMany: anotar('lineas.createMany', () => ({ count: 1 })),
      count: anotar('lineas.count', () => e.conConciliacion ?? 0),
    },
    tes_extracto_bancario: {
      update: anotar('extracto.update', () => ({})),
      deleteMany: anotar('extracto.deleteMany', () => ({ count: 1 })),
      create: anotar('extracto.create', () => ({ id: EXT })),
    },
    tes_movimientos: {
      findFirst: jest.fn().mockImplementation(({ where }: { where: { origen_tipo?: string } }) => {
        if (where.origen_tipo === 'CONCILIACION_AJUSTE') {
          orden.push('movimiento.yaCreado');
          return Promise.resolve(e.movimientoYaCreado ?? null);
        }
        orden.push('movimiento.findFirst');
        return Promise.resolve(e.movimiento === undefined ? movimiento() : e.movimiento);
      }),
      create: jest.fn().mockImplementation(({ data }: { data: Record<string, unknown> }) => {
        orden.push('movimiento.create');
        return Promise.resolve({ id: MOV, ...data });
      }),
    },
    tes_movimiento_det: { create: anotar('det.create', () => ({})) },
    tes_cuentas: { update: anotar('cuenta.update', () => ({})) },
    tes_categorias: { findMany: anotar('categorias.findMany', () => e.categorias ?? [{ id: CAT, tipo: 'AMBOS', activo: true, empresa_id: EMP, is_sistema: false }]) },
  };
  const prisma = {
    $transaction: jest.fn().mockImplementation((cb: (t: typeof tx) => unknown) => {
      orden.push('$transaction');
      return cb(tx);
    }),
    tes_extracto_lineas: {
      findFirst: jest.fn().mockResolvedValue(e.linea === undefined ? linea() : e.linea),
      findMany: jest.fn().mockResolvedValue(e.lineas ?? []),
      update: jest.fn().mockResolvedValue({}),
    },
    tes_extracto_bancario: {
      findFirst: jest.fn().mockResolvedValue(e.extracto === undefined ? extracto() : e.extracto),
      findMany: jest.fn().mockResolvedValue(e.extractos ?? []),
      update: jest.fn().mockResolvedValue({}),
    },
    tes_movimientos: { findMany: jest.fn().mockResolvedValue(e.movimientos ?? []), groupBy: jest.fn().mockResolvedValue(e.grupos ?? []) },
    tes_categorias: { findMany: jest.fn().mockResolvedValue(e.categorias ?? [{ id: CAT, tipo: 'AMBOS', activo: true, empresa_id: EMP, is_sistema: false }]) },
    tes_cuentas: {
      findFirst: jest.fn().mockResolvedValue(e.cuenta === undefined ? { id: CTA, empresa_id: EMP, moneda: 'PYG', activo: true } : e.cuenta),
      findMany: jest.fn().mockResolvedValue([]),
    },
    cont_documentos: { findMany: jest.fn().mockResolvedValue(e.documentos ?? []), findFirst: jest.fn().mockResolvedValue(e.documento ?? null) },
    audit_logs: { findFirst: jest.fn().mockResolvedValue(e.constancia ?? null) },
  };
  const aiProvider = { completar: e.completar ?? jest.fn() };
  const contabilidad = {
    integrarMovimientoTesoreria:
      e.integrador ??
      jest.fn().mockImplementation(() => {
        orden.push('integrar');
        return Promise.resolve({ generado: true });
      }),
  };
  const categorias = { findAll: jest.fn().mockResolvedValue(e.categoriasFindAll ?? []) };
  const aiConfig = {
    getConfigEfectiva: jest
      .fn()
      .mockResolvedValue({ api_key: e.apiKey === undefined ? 'k' : e.apiKey, proveedor: 'anthropic', modelo: 'x', credencial_modo: 'PROPIA', credencial_propia: true }),
  };
  const service = new TesConciliacionService(prisma as never, aiProvider as never, contabilidad as never, categorias as never, aiConfig as never);
  return { service, prisma, tx, orden, aiProvider, contabilidad, categorias, aiConfig };
}

/** El error que lanza la promesa, con `status` y el cuerpo estructurado; `null` si no falla. */
export const errorDe = async (p: Promise<unknown>): Promise<Record<string, unknown> | null> => {
  try {
    await p;
    return null;
  } catch (e) {
    const http = e as { getStatus?: () => number; getResponse?: () => unknown };
    const cuerpo = http.getResponse?.();
    return { status: http.getStatus?.(), ...(typeof cuerpo === 'object' ? (cuerpo as object) : { message: cuerpo }) };
  }
};
