'use strict';

const removeDuplicates = async ({ storeService, userId, id, search, }) => {
    const reports = await storeService.getAllReportsById(id, userId);
    const duplicateIds = getDuplicateRequestIds(search, reports);
    if (duplicateIds.length) {
        await Promise.all(duplicateIds.map(async (duplicateId) => {
            await storeService.removeReport(duplicateId, userId);
        }));
    }
};
/**
 * Gets the execution IDs of duplicate requests
 * - Checks whether the request query are the same
 *
 * @param {string} newReportSearchParams
 * @param {UserReportData[]} existingReports
 * @return {string[]}  ids of the duplicate requests
 */
const getDuplicateRequestIds = (newReportSearchParams, existingReports) => {
    const duplicates = [];
    const newQueryParams = new URLSearchParams(newReportSearchParams);
    existingReports.forEach((existingReportData) => {
        const matches = [];
        const search = existingReportData.url?.request?.search || '';
        const existingQueryParams = new URLSearchParams(search);
        const { executionId } = existingReportData;
        if (existingQueryParams.entries.length === newQueryParams.entries.length) {
            newQueryParams.forEach((newValue, newKey) => {
                const match = existingQueryParams.has(newKey, newValue);
                matches.push(match);
            });
        }
        if (matches.every(Boolean) && executionId) {
            duplicates.push(executionId);
        }
    });
    return duplicates;
};

exports.getDuplicateRequestIds = getDuplicateRequestIds;
exports.removeDuplicates = removeDuplicates;
//# sourceMappingURL=reportStoreHelper.js.map
