"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkExchangePolicy = checkExchangePolicy;
const schema_to_yup_1 = require("schema-to-yup");
/**
 * Helper function to safely extract validation errors from a Yup ValidationError.
 *
 * @param error - The error object to extract validation errors from
 * @returns An array of error objects, each containing:
 *   - message: The error message string
 *   - path: The path to the invalid field
 *   - value: The invalid value
 *
 * Returns an empty array if:
 * - The error is not a valid Yup ValidationError
 * - The error doesn't have an `inner` property
 * - The `inner` property is not an array
 */
function extractValidationErrors(error) {
    if (error &&
        typeof error === "object" &&
        "inner" in error &&
        Array.isArray(error.inner)) {
        return error.inner.map((e) => {
            // Extract only the needed properties from the error object
            if (e && typeof e === "object") {
                return {
                    message: "message" in e ? String(e.message) : "",
                    path: e.path || "",
                    value: e.value || undefined
                };
            }
            return { message: "", path: "", value: undefined };
        });
    }
    return [];
}
function checkExchangePolicy(offerData, rules) {
    var _a, _b, _c;
    let baseSchema;
    const metadataType = (_a = offerData.metadata) === null || _a === void 0 ? void 0 : _a.type;
    if (!rules.yupSchema.metadataType ||
        metadataType === rules.yupSchema.metadataType) {
        baseSchema = (0, schema_to_yup_1.buildYup)(rules.yupSchema, rules.yupConfig);
    }
    else {
        // For multiple schemas, use the one matching metadata.type
        const rulesTemplate = (_b = rules.yupSchemas) === null || _b === void 0 ? void 0 : _b.find((schema) => schema.metadataType === metadataType);
        if (!rulesTemplate) {
            return {
                isValid: false,
                errors: [
                    {
                        message: `Unsupported metadata type: ${String(metadataType)}`,
                        path: "metadata.type",
                        value: metadataType
                    }
                ]
            };
        }
        baseSchema = (0, schema_to_yup_1.buildYup)(rulesTemplate, rules.yupConfig);
    }
    let result = {
        isValid: true,
        errors: []
    };
    try {
        baseSchema.validateSync(offerData, { abortEarly: false });
    }
    catch (e) {
        result = {
            isValid: false,
            errors: extractValidationErrors(e)
        };
    }
    if (metadataType === "BUNDLE") {
        // For BUNDLE metadata, check each item in the bundle
        const bundleItems = ((_c = offerData.metadata) === null || _c === void 0 ? void 0 : _c.items) || [];
        if (bundleItems.length === 0) {
            // An empty bundle is semantically invalid
            result.isValid = false;
            result.errors = result.errors.concat([
                {
                    message: "Bundle metadata must contain at least one item.",
                    path: "metadata.items",
                    value: bundleItems
                }
            ]);
        }
        else {
            for (const item of bundleItems) {
                const itemType = item.type;
                const itemRulesTemplate = Array.isArray(rules.yupSchemas)
                    ? rules.yupSchemas.find((schema) => schema.metadataType === itemType)
                    : undefined;
                const itemSchema = itemRulesTemplate
                    ? (0, schema_to_yup_1.buildYup)(itemRulesTemplate, rules.yupConfig)
                    : undefined;
                if (itemSchema) {
                    try {
                        itemSchema.validateSync(item, { abortEarly: false });
                    }
                    catch (e) {
                        result.isValid = false;
                        result.errors = result.errors.concat(extractValidationErrors(e));
                    }
                }
            }
        }
        // Ensure bundle contains at least one ITEM_PRODUCT_V1 item,
        // as required by the UI logic to extract exchange policy and shipping data.
        const hasRequiredProductItem = bundleItems.some((item) => item.type === "ITEM_PRODUCT_V1");
        if (!hasRequiredProductItem) {
            result.isValid = false;
            result.errors = result.errors.concat({
                message: "Bundle metadata must contain at least one ITEM_PRODUCT_V1 item to provide exchange policy and shipping information.",
                path: "metadata.items",
                value: bundleItems
            });
        }
    }
    return result;
}
//# sourceMappingURL=checkExchangePolicy.js.map