// (C) 2026 GoodData Corporation
import { areObjRefsEqual } from "@gooddata/sdk-model";
import { getActiveTab, getTabOrActive } from "../tabsState.js";
import { parametersInitialState } from "./parametersState.js";
const addParameter = (state, action) => {
    const activeTab = getActiveTab(state);
    if (!activeTab) {
        return;
    }
    const { parameter, workspaceDefault } = action.payload;
    const tabParameters = activeTab.parameters ?? parametersInitialState;
    if (tabParameters.parameters.some((entry) => areObjRefsEqual(entry.parameter.ref, parameter.ref))) {
        return;
    }
    activeTab.parameters = {
        parameters: [
            ...tabParameters.parameters,
            { parameter, runtimeOverride: parameter.value ?? workspaceDefault },
        ],
    };
};
const setParameterRuntimeValue = (state, action) => {
    setRuntimeOverride(state, action.payload);
};
const setParameterRuntimeValues = (state, action) => {
    for (const entry of action.payload.values) {
        setRuntimeOverride(state, entry, action.payload.tabLocalIdentifier);
    }
};
const removeParameter = (state, action) => {
    const activeTab = getActiveTab(state);
    if (!activeTab?.parameters) {
        return;
    }
    activeTab.parameters = {
        parameters: activeTab.parameters.parameters.filter((entry) => !areObjRefsEqual(entry.parameter.ref, action.payload.ref)),
    };
};
function setRuntimeOverride(state, { ref, value }, tabLocalIdentifier) {
    const tab = getTabOrActive(state, tabLocalIdentifier);
    if (!tab?.parameters) {
        return;
    }
    const entry = tab.parameters.parameters.find((item) => areObjRefsEqual(item.parameter.ref, ref));
    if (entry && entry.runtimeOverride !== value) {
        entry.runtimeOverride = value;
    }
}
export const parametersReducers = {
    addParameter,
    setParameterRuntimeValue,
    setParameterRuntimeValues,
    removeParameter,
};
