// (C) 2022-2026 GoodData Corporation
import { call, put, select } from "redux-saga/effects";
import { idRef } from "@gooddata/sdk-model";
import { invalidQueryArguments } from "../events/general.js";
import { createCachedQueryService } from "../store/_infra/queryService.js";
import { selectCatalogFacts, selectCatalogMeasures } from "../store/catalog/catalogSelectors.js";
import { catalogActions } from "../store/catalog/index.js";
export const QueryMetricsAndFactsService = createCachedQueryService("GDC.DASH/QUERY.METRICS_AND_FACTS", queryService, (_query) => "metrics_and_facts");
async function loadMetricsAndFacts({ backend, workspace, config }) {
    const availability = config?.objectAvailability;
    const options = {
        excludeTags: (availability?.excludeObjectsWithTags ?? []).map((tag) => idRef(tag)),
        includeTags: (availability?.includeObjectsWithTags ?? []).map((tag) => idRef(tag)),
        types: ["fact", "measure"],
        loadGroups: false,
    };
    return backend.workspace(workspace).catalog().withOptions(options).load();
}
function* queryService(ctx, query) {
    const metrics = yield select(selectCatalogMeasures);
    const facts = yield select(selectCatalogFacts);
    // metrics and facts were loaded during dashboard initialization in initializeDashboardHandler
    // or by previous of this (sic) cached query that stores the result in the catalog slice as well
    if (metrics?.length > 0 && facts?.length > 0) {
        return {
            metrics,
            facts,
        };
    }
    const { correlationId } = query;
    const catalog = yield call(loadMetricsAndFacts, ctx);
    if (!catalog) {
        throw invalidQueryArguments(ctx, `Cannot find any metrics and facts`, correlationId);
    }
    // cache the results into catalog slice to be usable by other selectors without necessity to call
    // this query explicitly first
    yield put(catalogActions.setCatalogMeasuresAndFacts({
        facts: catalog.facts(),
        measures: catalog.measures(),
    }));
    return {
        metrics: catalog.measures(),
        facts: catalog.facts(),
    };
}
