import { RequisicionesService } from './requisiciones.service';

/** Prisma falso del circuito de aprobación, compartido por el spec del workflow y la matriz de configuración. */
export const SUC = 'aaaaaaaa-0000-4000-8000-000000000001';
export const PERFIL_1 = 'bbbbbbbb-0000-4000-8000-000000000001';
export const PERFIL_2 = 'bbbbbbbb-0000-4000-8000-000000000002';
export const cuerpo = (e: any) => e.getResponse();

export async function error(p: Promise<unknown>): Promise<any> {
  try {
    await p;
  } catch (e) {
    return e;
  }
  throw new Error('Se esperaba un error y no hubo');
}

export const cfg = (nivel: number, desde: number, hasta: number | null, perfil = nivel === 1 ? PERFIL_1 : PERFIL_2) => ({
  id: `cfg-${nivel}`,
  nivel,
  perfil_id: perfil,
  monto_desde: desde,
  monto_hasta: hasta,
  activo: true,
});

export const ap = (nivel: number, estado = 'pendiente', perfil = nivel === 1 ? PERFIL_1 : PERFIL_2) => ({
  id: `ap-${nivel}`,
  nivel,
  estado,
  perfil_id: perfil,
});

export interface Opts {
  estado?: string;
  origen?: string;
  total?: number;
  det?: unknown[];
  configs?: any[];
  aprobaciones?: any[];
  perfilesUsuario?: string[];
  ordenes?: any[];
  habilitada?: boolean;
  tieneCrear?: boolean;
}

export function armar(o: Opts = {}) {
  const orden: string[] = [];
  const aprobaciones = o.aprobaciones ?? [];
  const req = {
    id: 'req-1',
    empresa_id: 'emp-1',
    estado: o.estado ?? 'borrador',
    origen_tipo: o.origen ?? 'compra',
    total_para_aprobacion: o.total ?? 100,
    updated_at: new Date('2026-10-05T12:00:00.000Z'),
    requisicion_det: o.det ?? [{ id: 'det-1' }],
  };
  const tx: any = {
    $executeRaw: jest.fn().mockImplementation(async (_s: unknown, clave: string) => {
      orden.push(`lock:${clave}`);
    }),
    config_compras: { findUnique: jest.fn().mockResolvedValue({ habilitar_requisicion_compra: o.habilitada ?? true }), create: jest.fn() },
    empresas_sucursales: { findFirst: jest.fn().mockImplementation(async ({ where }: any) => ({ id: where.id })) },
    productos: { findFirst: jest.fn() },
    requisicion_cab: {
      findFirst: jest.fn().mockImplementation(async (args: any) => {
        if (args?.select?.numero_requisicion) return null;
        orden.push('relectura');
        return o.estado === 'inexistente' ? null : req;
      }),
      findUniqueOrThrow: jest.fn().mockResolvedValue(req),
      create: jest.fn().mockResolvedValue({ ...req, id: 'req-1' }),
      update: jest.fn().mockResolvedValue(undefined),
    },
    requisicion_det: { createMany: jest.fn().mockResolvedValue(undefined), deleteMany: jest.fn().mockResolvedValue(undefined) },
    requisicion_aprobacion: {
      findMany: jest.fn().mockResolvedValue(aprobaciones),
      deleteMany: jest.fn().mockResolvedValue(undefined),
      createMany: jest.fn().mockResolvedValue(undefined),
      update: jest.fn().mockResolvedValue(undefined),
      updateMany: jest.fn().mockResolvedValue(undefined),
    },
    requisicion_aprobacion_config: { findMany: jest.fn().mockResolvedValue(o.configs ?? []) },
    usuario_perfiles: {
      findFirst: jest.fn().mockImplementation(async ({ where }: any) => ((o.perfilesUsuario ?? []).includes(where.perfil_id) ? { id: 'up' } : null)),
    },
    usuario: { findUnique: jest.fn().mockResolvedValue({ is_superadmin: false }) },
    perfiles_privilegios: { findFirst: jest.fn().mockResolvedValue(o.tieneCrear === false ? null : { id: 'pp' }) },
    orden_compra_cab: { findMany: jest.fn().mockResolvedValue(o.ordenes ?? []) },
    requisicion_historial: { create: jest.fn().mockResolvedValue(undefined) },
  };
  const prisma: any = { $transaction: jest.fn().mockImplementation(async (cb: any) => cb(tx)), ...tx };
  const service = new RequisicionesService(prisma, {} as any, { logEnTransaccion: jest.fn() } as any);
  jest.spyOn(service, 'findOne').mockResolvedValue({ id: 'req-1' } as any);
  return { service, tx, prisma, orden, req };
}

export const hist = (tx: any) => tx.requisicion_historial.create.mock.calls.map((c: any[]) => c[0].data);
