import { Operator } from "@limetech/lime-web-components";
/**
 * Build a parsed explorer destination for a filter, optionally
 * narrowing it with extra expressions AND-combined onto the filter's
 * own expression. Use this when navigating imperatively via the
 * `Navigator` service so the host SPA stays on the page (no full
 * reload).
 * @param filter - the filter set whose limetype and id form the
 * explorer path. When `undefined`, the function returns
 * `{ path: '#' }` so callers can wire it into a link without a
 * special-case branch.
 * @param extraExpressions - expressions to AND onto the filter's own
 * expression. The chart passes `{ key: groupBy, op: '=', exp: item }`
 * here, info-tile passes a back-reference constraint when the widget
 * is on an object card. Order matters in the resulting AND: extras
 * come before the filter's own expression.
 * @returns `path` plus, when there's any filter expression to apply,
 * `query.filter` holding the combined expression as a raw object (the
 * navigator stringifies and URL-encodes it when generating the URL).
 */
export function buildExplorerLocation(filter, extraExpressions = []) {
    if (!filter) {
        return { path: '#' };
    }
    const path = ['explorer', filter.limetype, filter.id].join('/');
    const combined = combineExpressions(filter.filter, extraExpressions);
    return combined ? { path, query: { filter: combined } } : { path };
}
/**
 * Build a Lime CRM explorer href for a filter, optionally narrowing it
 * with extra expressions AND-combined onto the filter's own expression.
 *
 * Used by widgets like `limebb-info-tile` to render anchor `<a>` links
 * to a filtered list. For imperative navigation prefer
 * {@link buildExplorerLocation} together with the `Navigator` service.
 * @param filter - the filter set whose limetype and id form the
 * explorer href. When `undefined`, the function returns `'#'` so
 * callers can wire it into a link without a special-case branch.
 * @param extraExpressions - expressions to AND onto the filter's own
 * expression, with the same ordering and use-cases as
 * {@link buildExplorerLocation}.
 * @returns an explorer href such as
 * `explorer/{limetype}/{filterId}?filter=<URL-encoded JSON>`, or
 * `'#'` when `filter` is `undefined`.
 */
export function buildExplorerHref(filter, extraExpressions = []) {
    const { path, query } = buildExplorerLocation(filter, extraExpressions);
    if (!query) {
        return path;
    }
    const search = Object.entries(query)
        .map(([key, value]) => `${key}=${encodeURIComponent(JSON.stringify(value))}`)
        .join('&');
    return `${path}?${search}`;
}
function combineExpressions(filter, extras) {
    const all = [...extras, filter].filter((exp) => exp !== undefined);
    if (all.length === 0) {
        return undefined;
    }
    if (all.length === 1) {
        return all[0];
    }
    return {
        op: Operator.AND,
        exp: all,
    };
}
