"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateSortQuery = exports.generateSortSort = exports.getSortOption = exports.getSortOptions = void 0;
const getSortOptions = (options) => {
    const { provider } = options;
    const visibilityMode = provider.mode;
    return options.config.sort
        .sort((a, b) => {
        const aInt = typeof a.position === "string" ? parseInt(a.position, 10) : a.position;
        const bInt = typeof b.position === "string" ? parseInt(b.position, 10) : b.position;
        return aInt - bInt;
    })
        .filter(({ visibility }) => ["all", visibilityMode].includes(visibility));
};
exports.getSortOptions = getSortOptions;
const getSortOption = (options) => {
    var _a;
    const sortOptions = (0, exports.getSortOptions)(options);
    return ((_a = sortOptions.find(({ handle }) => { var _a; return handle === options.sortOption || handle === ((_a = options.query) === null || _a === void 0 ? void 0 : _a.sort); })) !== null && _a !== void 0 ? _a : sortOptions[0]);
};
exports.getSortOption = getSortOption;
const generateSortSort = (options) => {
    const { provider, curation, sortOption } = options;
    // curation positions are only applied for the default `collections.position` or `_score` sort
    // if the sort is something else, apply a normal sort which applies what the user has requested
    if (provider.mode !== "instant-search") {
        if (sortOption && !["_score", "collections.position"].includes(sortOption.field)) {
            if (["price_min", "price_max"].includes(sortOption.field) && provider.market) {
                return [{ [`${sortOption.field}_market_${provider.market}`]: sortOption.direction }];
            }
            return [{ [sortOption.field]: sortOption.direction }];
        }
    }
    const sorts = [];
    // collection curation pin sorting
    if (provider.mode === "collection" && provider.collectionHandle) {
        if (curation === null || curation === void 0 ? void 0 : curation.collectionHandle) {
            const queriesMust = [
                { term: { "curations.collectionHandle.keyword": curation.collectionHandle } },
            ];
            const queriesMustNot = [];
            if (provider.market) {
                queriesMust.push({ term: { "curations.markets.keyword": provider.market } });
            }
            else {
                queriesMustNot.push({ exists: { field: "curations.markets.keyword" } });
            }
            sorts.push({
                "curations.position": {
                    unmapped_type: "long",
                    order: "asc",
                    nested: {
                        path: "curations",
                        filter: {
                            bool: Object.assign({ must: queriesMust }, (queriesMustNot.length > 0 ? { must_not: queriesMustNot } : {})),
                        },
                    },
                },
            });
        }
    }
    // search curation pin sorting
    if (provider.mode === "search" || provider.mode === "instant-search") {
        if (curation === null || curation === void 0 ? void 0 : curation.searchTerm) {
            const queriesMust = [
                { term: { "curations.searchTerm.keyword": curation.searchTerm.toLowerCase() } },
            ];
            const queriesMustNot = [];
            if (provider.market) {
                queriesMust.push({ term: { "curations.markets.keyword": provider.market } });
            }
            else {
                queriesMustNot.push({ exists: { field: "curations.markets.keyword" } });
            }
            sorts.push({
                "curations.position": {
                    unmapped_type: "long",
                    order: "asc",
                    nested: {
                        path: "curations",
                        filter: {
                            bool: Object.assign({ must: queriesMust }, (queriesMustNot.length > 0 ? { must_not: queriesMustNot } : {})),
                        },
                    },
                },
            });
        }
    }
    // curation boost sorting
    if (curation) {
        if (0 < curation.boosting.groupings.length) {
            const groupings = curation.boosting.groupings.sort((a, b) => (a.position > b.position ? 1 : -1));
            for (const grouping of groupings) {
                try {
                    const query = JSON.parse(grouping.query);
                    if (query)
                        sorts.push(query);
                }
                catch (_a) {
                    console.error(`query could not be parsed for boost grouping`, grouping);
                }
            }
        }
        if (0 < curation.boosting.sortings.length) {
            const sortings = curation.boosting.sortings.sort((a, b) => (a.position > b.position ? 1 : -1));
            for (const sorting of sortings) {
                try {
                    let query = JSON.parse(sorting.query);
                    if (provider.market && sorting.field === "inventory_total") {
                        query = { [`inventory_quantity_market_${provider.market}`]: query.inventory_total };
                    }
                    if (provider.market && sorting.field === "price") {
                        query = { [`price_min_market_${provider.market}`]: query.price_min };
                    }
                    if (query) {
                        sorts.push(query);
                    }
                }
                catch (_b) {
                    console.error(`query could not be parsed for boost sorting`, sorting);
                }
            }
        }
    }
    // default sorting - use _score for all modes
    sorts.push("_score");
    return sorts;
};
exports.generateSortSort = generateSortSort;
const generateSortQuery = (options) => {
    var _a;
    const { provider, curation, sortOption } = options;
    if (!curation || curation.id.includes("global"))
        return { match_all: {} };
    const curationField = curation.type === "collection" ? "collectionHandle" : "searchTerm";
    const curationValue = curation.type === "collection" ? curation.collectionHandle : (_a = curation.searchTerm) === null || _a === void 0 ? void 0 : _a.toLowerCase();
    const queriesMust = [
        { term: { [`curations.${curationField}.keyword`]: curationValue } },
        { term: { "curations.hidden": true } },
    ];
    const queriesMustNot = [];
    if (provider.market) {
        queriesMust.push({ term: { "curations.markets.keyword": provider.market } });
    }
    else {
        queriesMustNot.push({ exists: { field: "curations.markets.keyword" } });
    }
    return {
        bool: {
            must_not: [
                {
                    nested: {
                        path: "curations",
                        query: {
                            bool: Object.assign({ must: queriesMust }, (queriesMustNot.length > 0 ? { must_not: queriesMustNot } : {})),
                        },
                    },
                },
                // hide callout when not sorting by _score or collections.position
                ...(sortOption && !["_score", "collections.position"].includes(sortOption.field)
                    ? [{ term: { type: "callout" } }]
                    : []),
            ],
        },
    };
};
exports.generateSortQuery = generateSortQuery;
//# sourceMappingURL=sortOption.js.map