import Ajv2020Import from "ajv/dist/2020.js";
import envelopeSchema from "./schemas/task-state-event-envelope.v1.json" with { type: "json" };
import eventSchema from "./schemas/task-state-event.v1.json" with { type: "json" };
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ajv/dist/2020 default export shape varies by bundler
const Ajv2020Ctor = Ajv2020Import.default ?? Ajv2020Import;
let compiled = null;
function loadValidator() {
    if (compiled) {
        return compiled;
    }
    const ajv = new Ajv2020Ctor({ strict: false, allErrors: true });
    ajv.addSchema(envelopeSchema);
    compiled = ajv.compile(eventSchema);
    return compiled;
}
function formatAjvErrors(errors) {
    if (!errors?.length) {
        return ["validation failed"];
    }
    return errors.map((e) => {
        const p = e.instancePath?.length ? e.instancePath : "(root)";
        return `${p}: ${e.message ?? e.keyword ?? "error"}`;
    });
}
export function validateTaskStateEvent(input) {
    const validate = loadValidator();
    if (!validate(input)) {
        return { ok: false, errors: formatAjvErrors(validate.errors) };
    }
    return { ok: true, data: input };
}
