"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.addDynamicSlugValidation = void 0;
const slugs_1 = require("../../../items/_internal/slugs");
const util_1 = require("../../../util");
/**
 * add slug max length and unique validation to schema
 * based on the orgUrlKey
 * @param schema
 * @param options
 * @returns
 */
const addDynamicSlugValidation = (schema, options) => {
    var _a;
    const _slug = (0, util_1.cloneObject)((_a = schema.properties) === null || _a === void 0 ? void 0 : _a._slug);
    if (!_slug) {
        return schema;
    }
    // add max length to slug
    let { orgUrlKey } = options;
    // orgUrlKey is undefined in Enterprise
    if (!orgUrlKey) {
        orgUrlKey = "";
    }
    // ensure orgUrlKey is lowercase
    orgUrlKey = orgUrlKey.toLowerCase();
    _slug.maxLength = (0, slugs_1.getSlugMaxLength)(orgUrlKey);
    // add conditional validation to ensure slug is unique
    const allOf = (0, util_1.cloneObject)(schema.allOf) || [];
    const { pattern } = _slug;
    // remove pattern from base schema so the form doesn't always apply the pattern
    // validation. We will add it back to the allOf conditionally
    delete _slug.pattern;
    const { id } = options;
    allOf.push({
        // only enforce the pattern if slug has been entered
        if: { properties: { _slug: { minLength: 1 } } },
        then: { properties: { _slug: { pattern } } },
    }, {
        // only do async isUniqueSlug check if the slug is valid
        if: { properties: { _slug: { pattern } } },
        then: {
            // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
            properties: { _slug: { isUniqueSlug: { id, orgUrlKey } } },
        },
    });
    const clone = (0, util_1.cloneObject)(schema);
    clone.properties._slug = _slug;
    clone.allOf = allOf;
    return clone;
};
exports.addDynamicSlugValidation = addDynamicSlugValidation;
//# sourceMappingURL=addDynamicSlugValidation.js.map