'use strict';

var sessionHelper = require('../../../utils/sessionHelper.js');
var dateHelper = require('../../../utils/dateHelper.js');
var queryMappers = require('../../../utils/queryMappers.js');
var definitionUtils = require('../../../utils/definitionUtils.js');
var utils = require('../../_inputs/date-range/utils.js');
var _enum = require('../filter-input/enum.js');

/**
 * -------------------------------------------------------------------------------------
 * Public API
 * -------------------------------------------------------------------------------------
 */
function buildAppliedFilters(req, sessionKey, fields) {
    const currentReportFiltersSearch = sessionHelper.getActiveJourneyValue(req, sessionKey, 'currentReportFiltersSearch');
    let appliedFilters = [];
    if (currentReportFiltersSearch) {
        const query = queryMappers.qsToQueryObject(currentReportFiltersSearch, 'filters.');
        const filterFields = definitionUtils.getFieldsWithFilters(fields);
        appliedFilters = buildAppliedFilterChips(query, filterFields);
    }
    return appliedFilters;
}
function buildAppliedFilterChips(query, fields) {
    return fields
        .filter((field) => Boolean(field.filter))
        .map((field) => buildChipForField(field, query))
        .filter(Boolean);
}
/**
 * -------------------------------------------------------------------------------------
 * Orchestrator (semantic parity with Selected Filters)
 * -------------------------------------------------------------------------------------
 */
function buildChipForField(field, query) {
    const filter = field.filter;
    const baseKey = `filters.${field.name}`;
    switch (filter.type.toLowerCase()) {
        case _enum.FilterType.dateRange.toLowerCase():
            return buildDateRangeChip(field, baseKey, query);
        case _enum.FilterType.granularDateRange.toLowerCase():
            return buildGranularDateRangeChip(field, baseKey, query);
        case _enum.FilterType.multiselect.toLowerCase():
            return buildMultiSelectChip(field, baseKey, query);
        case _enum.FilterType.date.toLowerCase():
            return buildDateChip(field, baseKey, query);
        default:
            return buildSingleValueChip(field, baseKey, query);
    }
}
/**
 * -------------------------------------------------------------------------------------
 * Builders
 * -------------------------------------------------------------------------------------
 */
/**
 * Date range
 * - Renders if either bound exists
 * - Missing bounds rendered as 'unset'
 */
function buildDateRangeChip(field, baseKey, query) {
    const duration = query[`${baseKey}.relative-duration`];
    const start = query[`${baseKey}.start`];
    const end = query[`${baseKey}.end`];
    // Render if anything date-related is set
    if (!duration && !start && !end)
        return null;
    // Always show the explicit range
    let displayValue = `${dateHelper.formatDateOrUnset(start)} - ${dateHelper.formatDateOrUnset(end)}`;
    // Append duration if present
    if (duration && duration !== 'None') {
        const durationLabel = getDisplayLabel(field.filter, duration);
        displayValue = `${displayValue} / ${durationLabel}`;
    }
    return {
        displayName: field.display,
        displayValue,
        reset: {
            keys: Object.keys(query).filter((key) => key.startsWith(baseKey)),
        },
    };
}
/**
 * Granular date range
 * - Renders if quick-filter OR either bound exists
 * - Quick-filter takes precedence
 * - Missing values rendered as 'unset'
 */
function buildGranularDateRangeChip(field, baseKey, query) {
    const quick = query[`${baseKey}.quick-filter`];
    const granularity = query[`${baseKey}.granularity`];
    const start = query[`${baseKey}.start`];
    const end = query[`${baseKey}.end`];
    if (!quick && !start && !end)
        return null;
    let displayValue;
    if (quick && quick !== 'None') {
        displayValue = `${humanise(quick)} / ${granularity ?? 'unset'}`;
    }
    else {
        displayValue = `${dateHelper.formatDateOrUnset(start)} - ${dateHelper.formatDateOrUnset(end)} / ${granularity ?? 'unset'}`;
    }
    return {
        displayName: field.display,
        displayValue,
        reset: {
            keys: Object.keys(query).filter((key) => key.startsWith(baseKey)),
        },
    };
}
/**
 * Multiselect
 * - Combined into single chip
 * - Truncated after 3 values
 */
function buildMultiSelectChip(field, key, query) {
    const raw = query[key];
    let values = [];
    if (Array.isArray(raw)) {
        values = raw;
    }
    else if (raw) {
        values = [raw];
    }
    if (!values.length)
        return null;
    const labels = values.map((value) => getDisplayLabel(field.filter, value));
    const displayValue = labels.length > 3 ? `${labels.slice(0, 3).join(', ')} + ${labels.length - 3} more` : labels.join(', ');
    return {
        displayName: field.display,
        displayValue,
        reset: {
            keys: [key],
        },
    };
}
/**
 * Date
 */
function buildDateChip(field, key, query) {
    const value = query[key];
    if (!value || typeof value !== 'string')
        return null;
    const dateValue = dateHelper.apiDateToUi(value);
    return {
        displayName: field.display,
        displayValue: dateValue || value,
        reset: {
            keys: [key],
        },
    };
}
/**
 * Single value
 * - radio / select / text / autocomplete
 */
function buildSingleValueChip(field, key, query) {
    const value = query[key];
    if (!value)
        return null;
    return {
        displayName: field.display,
        displayValue: getDisplayLabel(field.filter, String(value)),
        reset: {
            keys: [key],
        },
    };
}
/**
 * -------------------------------------------------------------------------------------
 * Helpers
 * -------------------------------------------------------------------------------------
 */
function getDisplayLabel(filter, value) {
    if (filter.type === 'daterange') {
        const mapped = utils.mapRelativeValue(value);
        if (mapped) {
            return mapped;
        }
    }
    const staticOption = filter.staticOptions?.find((option) => option.name === value);
    return staticOption?.display ?? value;
}
function humanise(value) {
    return String(value).replace(/-/g, ' ');
}

exports.buildAppliedFilterChips = buildAppliedFilterChips;
exports.buildAppliedFilters = buildAppliedFilters;
//# sourceMappingURL=utils.js.map
