import { useQuery } from '@tanstack/react-query';
import { ConfigService } from 'udp-react-stencil-component-library';
import { apiMutate } from '../../utilities/useAxiosMutate';
const TAG_ASSOCIATION_ENDPOINT = 'udpTagAssociation/search';
const BASE_SEARCH_PAYLOAD = {
    pageNumber: 1,
    pageSize: 200,
    filterElements: [],
    filterGroups: [],
    orderElements: [],
    groupingType: '',
    groupProperty: [],
    groupOperationList: [],
    eagerLoad: true,
    logicalSearchOperator: 1,
};
const EMPTY_MAP = new Map();
const fetchTagAssociations = async (entityBusinessKeyPrefix) => {
    var _a;
    var _b;
    const res = (await apiMutate(ConfigService.productV1ApiUrl, TAG_ASSOCIATION_ENDPOINT, { method: 'post' }, {
        data: Object.assign(Object.assign({}, BASE_SEARCH_PAYLOAD), { getAll: true, filterElements: [
                {
                    searchField: 'entityBusinessKey',
                    searchOperator: 'STARTSWITH',
                    searchValue: entityBusinessKeyPrefix,
                },
            ] }),
    }));
    return (_b = (_a = res === null || res === void 0 ? void 0 : res.data) === null || _a === void 0 ? void 0 : _a.pageList) !== null && _b !== void 0 ? _b : [];
};
const buildTagMap = (associations) => {
    var _a;
    const map = new Map();
    for (const a of associations) {
        const id = (_a = a.entityBusinessKey) === null || _a === void 0 ? void 0 : _a.split('|')[1];
        const tag = a.udpTagAssociationUdpTag;
        if (!id || !tag)
            continue;
        const existing = map.get(id);
        if (existing) {
            existing.push(tag);
        }
        else {
            map.set(id, [tag]);
        }
    }
    return map;
};
/**
 * Fetch and cache tag associations for every record of a single entity type.
 *
 * Pass a type-only prefix ending in `|` — e.g.
 * `Univerus.Unity.Starter.Project.Models.ChargeCodeTask|`.
 *
 * Returns a `Map<entityId, UdpTag[]>` keyed by the GUID portion of the
 * business key. The query is shared across the app via TanStack Query, so
 * multiple components calling this hook with the same prefix dedupe to a
 * single request and stay in sync on invalidation.
 */
export const useTags = (entityBusinessKeyPrefix, options) => {
    var _a;
    const query = useQuery({
        queryKey: [TAG_ASSOCIATION_ENDPOINT, entityBusinessKeyPrefix],
        queryFn: () => fetchTagAssociations(entityBusinessKeyPrefix),
        enabled: (options === null || options === void 0 ? void 0 : options.enabled) !== false && !!entityBusinessKeyPrefix,
        select: buildTagMap,
    });
    return {
        tagMap: (_a = query.data) !== null && _a !== void 0 ? _a : EMPTY_MAP,
        isLoading: query.isLoading,
        error: query.error,
    };
};
//# sourceMappingURL=useTags.js.map