/**
 * Copyright IBM Corp. 2024, 2025
 */

import { Ajv } from 'ajv';

function validateSchema(
  data: any,
  schema: any,
): { valid: boolean; errors: any } {
  if (typeof schema === 'string') schema = JSON.parse(schema);
  if (typeof schema !== 'object' || schema === null)
    throw new Error('Invalid schema');

  const ajv = new Ajv();
  const validate = ajv.compile(schema);
  const valid = validate(data);
  return { valid, errors: validate.errors };
}

export function validSchemaAssertion(data: any, schema: any): void {
  const { valid, errors } = validateSchema(data, schema);
  if (!valid) {
    throw new Error(errors?.[0]?.message ?? 'Invalid schema');
  }
}

export function invalidSchemaAssertion(data: any, schema: any): void {
  const { valid } = validateSchema(data, schema);
  if (valid) {
    throw new Error('Schema is valid');
  }
}
