"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeLookupField = normalizeLookupField;
exports.ensureLookupLocalKeyUnwinds = ensureLookupLocalKeyUnwinds;
exports.applyLinkFieldUnwinds = applyLinkFieldUnwinds;
function normalizeLookupField(path) {
    if (!path) {
        return path;
    }
    var cleaned = path.replace(/\.\$/g, '');
    cleaned = cleaned.replace(/^[^\.]*\(.*?Lookup.*?\)\.?/, '');
    return cleaned;
}
function buildSafeSizeExpression(sourceExpr) {
    return { $size: { $cond: [{ $isArray: sourceExpr }, sourceExpr, []] } };
}
function ensureLookupLocalKeyUnwinds(options) {
    var _a = options || {}, query = _a.query, sizes = _a.sizes, lookupLocalKey = _a.lookupLocalKey, _b = _a.lookupAs, lookupAs = _b === void 0 ? '' : _b;
    if (!lookupLocalKey || typeof lookupLocalKey !== 'string') {
        return;
    }
    if (!query || !Array.isArray(query) || !sizes || !Array.isArray(sizes)) {
        return;
    }
    var unwindPathSeed = lookupLocalKey;
    // Some lookup local keys are stored without `.$` even when sourced from array paths.
    // Infer the array segment from lookup alias and synthesize the unwind marker.
    if (!unwindPathSeed.includes('.$') && typeof lookupAs === 'string' && lookupAs.includes('.$.')) {
        var inferredArrayPrefix = lookupAs.split('.$.')[0];
        if (inferredArrayPrefix) {
            if (unwindPathSeed.startsWith(inferredArrayPrefix + '.')) {
                unwindPathSeed = inferredArrayPrefix + '.$.' + unwindPathSeed.substring(inferredArrayPrefix.length + 1);
            }
            else {
                unwindPathSeed = inferredArrayPrefix + '.$';
            }
        }
    }
    if (!unwindPathSeed.includes('.$')) {
        return;
    }
    var fieldData = unwindPathSeed.split('.$');
    var fieldPath = '';
    var _loop_1 = function (i) {
        var _c;
        fieldPath += fieldData[i];
        var sizeKey = fieldPath.replace(/\./g, '_');
        if (!sizes.includes(sizeKey)) {
            sizes.push(sizeKey);
        }
        if (!query.some(function (a) { return a && a.$addFields && Object.keys(a.$addFields).includes('size_' + sizeKey); })) {
            var sourceExpr = '$' + fieldPath;
            query.push({ $addFields: (_c = {}, _c['size_' + sizeKey] = buildSafeSizeExpression(sourceExpr), _c) });
        }
        var unwindPath = '$' + fieldPath;
        if (!query.some(function (a) { return a && a.$unwind && a.$unwind.path === unwindPath; })) {
            query.push({ '$unwind': { path: unwindPath, preserveNullAndEmptyArrays: true } });
        }
    };
    for (var i = 0; i < fieldData.length - 1; i++) {
        _loop_1(i);
    }
}
function applyLinkFieldUnwinds(options) {
    var _a = options || {}, query = _a.query, sizes = _a.sizes, fieldsLink = _a.fieldsLink, _b = _a.selectedFields, selectedFields = _b === void 0 ? [] : _b, _c = _a.filterArrayFields, filterArrayFields = _c === void 0 ? [] : _c, _d = _a.groupsRow, groupsRow = _d === void 0 ? [] : _d;
    if (!query || !Array.isArray(query) || !sizes || !Array.isArray(sizes) || !Array.isArray(fieldsLink) || !fieldsLink.length) {
        return;
    }
    var leafByPath = new Map();
    (selectedFields || []).forEach(function (field) {
        if ((field === null || field === void 0 ? void 0 : field.fieldPath) && !leafByPath.has(field.fieldPath)) {
            leafByPath.set(field.fieldPath, field);
        }
    });
    (filterArrayFields || []).forEach(function (field) {
        if ((field === null || field === void 0 ? void 0 : field.fieldPath) && !leafByPath.has(field.fieldPath)) {
            leafByPath.set(field.fieldPath, field);
        }
    });
    (groupsRow || []).forEach(function (group) {
        var _a;
        if (((_a = group === null || group === void 0 ? void 0 : group.treeItem) === null || _a === void 0 ? void 0 : _a.fieldPath) && !leafByPath.has(group.treeItem.fieldPath)) {
            leafByPath.set(group.treeItem.fieldPath, group.treeItem);
        }
    });
    var hasUnwindPath = function (unwindPath) {
        return query.some(function (a) { return a && a.$unwind && a.$unwind.path === unwindPath; });
    };
    var ensureUnwindsForPath = function (targetPath) {
        if (!targetPath || typeof targetPath !== 'string' || !targetPath.includes('.$')) {
            return;
        }
        var leaf = leafByPath.get(targetPath);
        var fieldData = targetPath.split('.$');
        var fieldPath = '';
        var _loop_2 = function (i) {
            var _a, _b;
            fieldPath += fieldData[i];
            var lastSegment = fieldPath.split('.$')[fieldPath.split('.$').length - 1];
            var hasLookup = (lastSegment || '').includes('(Lookup') || ((leaf === null || leaf === void 0 ? void 0 : leaf.lookup_as) && fieldPath === leaf.lookup_as);
            if (hasLookup && (leaf === null || leaf === void 0 ? void 0 : leaf.lookup_collection) && (leaf === null || leaf === void 0 ? void 0 : leaf.lookup_as)) {
                ensureLookupLocalKeyUnwinds({
                    query: query,
                    sizes: sizes,
                    lookupLocalKey: leaf.lookup_local_key || '',
                    lookupAs: leaf.lookup_as || ''
                });
                var lookupAsRaw = leaf.lookup_as || '';
                var lookupAs_1 = lookupAsRaw.replace(/\.\$/g, '');
                var hasLookupStage = query.some(function (a) { return a && a.$lookup && a.$lookup.as === lookupAs_1; });
                if (!hasLookupStage) {
                    query.push({ $lookup: {
                            from: leaf.lookup_collection,
                            localField: normalizeLookupField(leaf.lookup_local_key || ''),
                            foreignField: normalizeLookupField(leaf.lookup_foreign_key || ''),
                            as: lookupAs_1
                        } });
                }
                var sizeKey_1 = lookupAsRaw.replace(/\.\$\./g, '_').replace(/\./g, '_');
                if (!query.some(function (a) { return a && a.$addFields && Object.keys(a.$addFields).includes('size_' + sizeKey_1); })) {
                    sizes.push(sizeKey_1);
                    var sourceExpr = '$' + lookupAs_1;
                    query.push({ $addFields: (_a = {}, _a['size_' + sizeKey_1] = buildSafeSizeExpression(sourceExpr), _a) });
                }
                var unwindPath = '$' + lookupAs_1;
                if (!hasUnwindPath(unwindPath)) {
                    query.push({ '$unwind': { path: unwindPath, preserveNullAndEmptyArrays: true } });
                }
            }
            else {
                var sizeKey_2 = fieldPath.replace(/\.\$\./g, '.').replace(/\./g, '_');
                if (!query.some(function (a) { return a && a.$addFields && Object.keys(a.$addFields).includes('size_' + sizeKey_2); })) {
                    sizes.push(sizeKey_2);
                    var sourceExpr = '$' + fieldPath.replace(/\.\$\./g, '.');
                    query.push({ $addFields: (_b = {}, _b['size_' + sizeKey_2] = buildSafeSizeExpression(sourceExpr), _b) });
                }
                var unwindPath = '$' + fieldPath.replace(/\.\$\./g, '.');
                if (!hasUnwindPath(unwindPath)) {
                    query.push({ '$unwind': { path: unwindPath, preserveNullAndEmptyArrays: true } });
                }
            }
            fieldPath += '.$';
        };
        for (var i = 0; i < fieldData.length - 1; i++) {
            _loop_2(i);
        }
    };
    (fieldsLink || [])
        .filter(function (a) { return a && a.field_first && a.field_second; })
        .forEach(function (link) {
        ensureUnwindsForPath(link.field_first);
        ensureUnwindsForPath(link.field_second);
    });
}

//# sourceMappingURL=report-builder-unwinds.js.map
