// engine/event-schema-validator/payload-validator.ts — Payload validation (SPEC-031)
import { getJsonType, typesMatch } from './helpers.js';
/**
 * Validate a payload object against the active contract schema.
 */
export function validatePayload(payload, contract) {
    const schema = contract.versions[contract.currentVersion];
    if (!schema) {
        return {
            valid: false,
            violations: [
                {
                    field: '(root)',
                    issue: `No schema found for version ${contract.currentVersion}`,
                },
            ],
        };
    }
    return validateAgainstSchema(payload, schema.jsonSchema);
}
/**
 * Validate a payload against a raw JSON Schema object.
 * Handles required fields and properties type checking (top-level only).
 */
export function validateAgainstSchema(payload, jsonSchema) {
    const violations = [];
    const required = Array.isArray(jsonSchema.required) ? jsonSchema.required : [];
    const properties = jsonSchema.properties !== null &&
        typeof jsonSchema.properties === 'object' &&
        !Array.isArray(jsonSchema.properties)
        ? jsonSchema.properties
        : {};
    for (const field of required) {
        if (!(field in payload)) {
            violations.push({ field, issue: `Required field '${field}' is missing from payload` });
        }
    }
    for (const [field, propSchema] of Object.entries(properties)) {
        if (!(field in payload)) {
            continue;
        }
        const expectedType = propSchema.type;
        if (!expectedType) {
            continue;
        }
        const actualType = getJsonType(payload[field]);
        if (!typesMatch(actualType, expectedType)) {
            violations.push({
                field,
                issue: `Field '${field}' has wrong type`,
                expectedType,
                actualType,
            });
        }
    }
    return { valid: violations.length === 0, violations };
}
//# sourceMappingURL=payload-validator.js.map