// (C) 2023-2026 GoodData Corporation
import { call, put, select } from "redux-saga/effects";
import { idRef } from "@gooddata/sdk-model";
import { attributeHierarchyModifiedEvent, } from "../../events/insight.js";
import { catalogActions } from "../../store/catalog/index.js";
import { selectObjectAvailabilityConfig } from "../../store/config/configSelectors.js";
import { loadDateHierarchyTemplates } from "../dashboard/initializeDashboardHandler/loadDateHierarchyTemplates.js";
const SupportedCatalogGranularity = [
    "GDC.time.day_in_week",
    "GDC.time.day_in_month",
    "GDC.time.day_in_quarter",
    "GDC.time.day_in_year",
    "GDC.time.week_in_quarter",
    "GDC.time.week_in_year",
    "GDC.time.month_in_quarter",
    "GDC.time.month_in_year",
    "GDC.time.quarter_in_year",
];
function loadCatalog(ctx, availability) {
    const { backend, workspace } = ctx;
    const options = {
        excludeTags: (availability.excludeObjectsWithTags ?? []).map((tag) => idRef(tag)),
        includeTags: (availability.includeObjectsWithTags ?? []).map((tag) => idRef(tag)),
        types: ["attribute", "fact", "measure", "dateDataset", "attributeHierarchy"],
        includeDateGranularities: SupportedCatalogGranularity,
        loadGroups: false,
    };
    return backend.workspace(workspace).catalog().withOptions(options).load();
}
export function* attributeHierarchyModifiedHandler(ctx, cmd) {
    const { correlationId } = cmd;
    const availability = yield select(selectObjectAvailabilityConfig);
    const catalog = yield call(loadCatalog, ctx, availability);
    const dateHierarchyTemplates = yield call(loadDateHierarchyTemplates, ctx);
    yield put(catalogActions.setCatalogItems({
        attributes: catalog.attributes(),
        dateDatasets: catalog.dateDatasets(),
        facts: catalog.facts(),
        measures: catalog.measures(),
        attributeHierarchies: catalog.attributeHierarchies(),
        dateHierarchyTemplates,
    }));
    return attributeHierarchyModifiedEvent(ctx, correlationId);
}
