// (C) 2022-2026 GoodData Corporation
import { call, select } from "redux-saga/effects";
import { areObjRefsEqual, serializeObjRef } from "@gooddata/sdk-model";
import { invalidQueryArguments } from "../events/general.js";
import { createCachedQueryService } from "../store/_infra/queryService.js";
import { selectPreloadedAttributesWithReferences } from "../store/tabs/filterContext/filterContextSelectors.js";
export const QueryAttributeDataSetService = createCachedQueryService("GDC.DASH/QUERY.DATA.SET.ATTRIBUTE", queryService, (query) => {
    const { payload: { displayForm }, } = query;
    return serializeObjRef(displayForm);
});
async function loadAttributeDataSetMeta(ctx, attributeRef, preloadedAttributesWithReferences) {
    const { backend, workspace } = ctx;
    // First try to get the dataSet from preloaded filters
    const dataSet = preloadedAttributesWithReferences?.find((attr) => areObjRefsEqual(attr.attribute.ref, attributeRef))?.dataSet;
    if (dataSet) {
        return dataSet;
    }
    // If dataSet is not in preloaded filters, fetch it from backend
    return backend.workspace(workspace).attributes().getAttributeDatasetMeta(attributeRef);
}
function* queryService(ctx, query) {
    const { payload: { displayForm }, correlationId, } = query;
    const preloadedAttributesWithReferences = yield select(selectPreloadedAttributesWithReferences);
    const attributeDataSet = yield call(loadAttributeDataSetMeta, ctx, displayForm, preloadedAttributesWithReferences);
    if (!attributeDataSet) {
        throw invalidQueryArguments(ctx, `Cannot find attribute data set for given displayForm`, correlationId);
    }
    return attributeDataSet;
}
//# sourceMappingURL=queryAttributeDataset.js.map