import Ajv from "ajv";

//#region src/validation/props-validation.ts
/**
* Validates that a props object is a valid JSON Schema
* Uses AJV to validate the schema structure without resolving references
*/
function validatePropsAsJsonSchema(props) {
	if (!props || typeof props === "object" && Object.keys(props).length === 0) return {
		isValid: true,
		errors: []
	};
	if (typeof props !== "object" || Array.isArray(props)) return {
		isValid: false,
		errors: [{
			field: "props",
			message: "Props must be a valid JSON Schema object",
			value: props
		}]
	};
	if (!props.type) return {
		isValid: false,
		errors: [{
			field: "props.type",
			message: "JSON Schema must have a \"type\" field"
		}]
	};
	if (props.type !== "object") return {
		isValid: false,
		errors: [{
			field: "props.type",
			message: "JSON Schema type must be \"object\" for component props",
			value: props.type
		}]
	};
	if (!props.properties || typeof props.properties !== "object") return {
		isValid: false,
		errors: [{
			field: "props.properties",
			message: "JSON Schema must have a \"properties\" object"
		}]
	};
	if (props.required !== void 0 && !Array.isArray(props.required)) return {
		isValid: false,
		errors: [{
			field: "props.required",
			message: "If present, \"required\" must be an array"
		}]
	};
	try {
		const schemaToValidate = { ...props };
		delete schemaToValidate.$schema;
		const schemaValidator = new Ajv({
			strict: false,
			validateSchema: true,
			addUsedSchema: false
		});
		if (!schemaValidator.validateSchema(schemaToValidate)) return {
			isValid: false,
			errors: (schemaValidator.errors || []).map((error) => ({
				field: `props${error.instancePath || ""}`,
				message: error.message || "Invalid schema"
			}))
		};
		return {
			isValid: true,
			errors: []
		};
	} catch (error) {
		return {
			isValid: false,
			errors: [{
				field: "props",
				message: `Schema validation failed: ${error instanceof Error ? error.message : "Unknown error"}`
			}]
		};
	}
}

//#endregion
export { validatePropsAsJsonSchema };