"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateFactory = void 0;
const logger_1 = require("../logger");
const hmac_validator_1 = require("../utils/hmac-validator");
const types_1 = require("../utils/types");
const http_1 = require("../../runtime/http");
const types_2 = require("../types");
const types_3 = require("./types");
const registry_1 = require("./registry");
const OPTIONAL_HANDLER_PROPERTIES = {
    subTopic: types_2.ShopifyHeader.SubTopic,
};
const HANDLER_PROPERTIES = {
    apiVersion: types_2.ShopifyHeader.ApiVersion,
    domain: types_2.ShopifyHeader.Domain,
    hmac: types_2.ShopifyHeader.Hmac,
    topic: types_2.ShopifyHeader.Topic,
    webhookId: types_2.ShopifyHeader.WebhookId,
    ...OPTIONAL_HANDLER_PROPERTIES,
};
function validateFactory(config) {
    return async function validate({ rawBody, ...adapterArgs }) {
        const request = await (0, http_1.abstractConvertRequest)(adapterArgs);
        const validHmacResult = await (0, hmac_validator_1.validateHmacFromRequestFactory)(config)({
            type: types_1.HmacValidationType.Webhook,
            rawBody,
            ...adapterArgs,
        });
        if (!validHmacResult.valid) {
            // Deprecated: this is for backwards compatibility with the old HMAC validation
            // This will be removed in the next major version, and missing_hmac will be returned instead of missing_header when the hmac is missing
            if (validHmacResult.reason === types_1.ValidationErrorReason.MissingHmac) {
                return {
                    valid: false,
                    reason: types_3.WebhookValidationErrorReason.MissingHeaders,
                    missingHeaders: [types_2.ShopifyHeader.Hmac],
                };
            }
            if (validHmacResult.reason === types_1.ValidationErrorReason.InvalidHmac) {
                const log = (0, logger_1.logger)(config);
                await log.debug("Webhook HMAC validation failed. Please note that events manually triggered from a store's Notifications settings will fail this validation. To test this, please use the CLI or trigger the actual event in a development store.");
            }
            return validHmacResult;
        }
        return checkWebhookHeaders(request.headers);
    };
}
exports.validateFactory = validateFactory;
function checkWebhookHeaders(headers) {
    const missingHeaders = [];
    const entries = Object.entries(HANDLER_PROPERTIES);
    const headerValues = entries.reduce((acc, [property, headerName]) => {
        const headerValue = (0, http_1.getHeader)(headers, headerName);
        if (headerValue) {
            acc[property] = headerValue;
        }
        else if (!(property in OPTIONAL_HANDLER_PROPERTIES)) {
            missingHeaders.push(headerName);
        }
        return acc;
    }, {});
    if (missingHeaders.length) {
        return {
            valid: false,
            reason: types_3.WebhookValidationErrorReason.MissingHeaders,
            missingHeaders,
        };
    }
    else {
        return {
            valid: true,
            ...headerValues,
            ...(headerValues.subTopic ? { subTopic: headerValues.subTopic } : {}),
            topic: (0, registry_1.topicForStorage)(headerValues.topic),
        };
    }
}
//# sourceMappingURL=validate.js.map