// (C) 2021-2026 GoodData Corporation
import { call, put, select } from "redux-saga/effects";
import { attributeFilterMoved } from "../../../events/filters.js";
import { invalidArgumentsProvided } from "../../../events/general.js";
import { dispatchDashboardEvent } from "../../../store/_infra/eventDispatcher.js";
import { selectFilterContextAttributeFilterItemByLocalId, selectFilterContextDraggableFilterIndexByRef, selectFilterContextFilters, } from "../../../store/tabs/filterContext/filterContextSelectors.js";
import { tabsActions } from "../../../store/tabs/index.js";
import { dispatchFilterContextChanged } from "../common.js";
export function* moveAttributeFilterHandler(ctx, cmd) {
    const { filterLocalId, index } = cmd.payload;
    // validate filterLocalId
    const affectedFilter = yield select(selectFilterContextAttributeFilterItemByLocalId(filterLocalId));
    if (!affectedFilter) {
        throw invalidArgumentsProvided(ctx, cmd, `Filter with filterLocalId ${filterLocalId} not found.`);
    }
    // validate target index
    const allFilters = yield select(selectFilterContextFilters);
    const maximalTargetIndex = allFilters.length - 1;
    if (index > maximalTargetIndex || index < -1) {
        throw invalidArgumentsProvided(ctx, cmd, `Invalid index (${index}) provided, it must be between -1 and ${maximalTargetIndex}`);
    }
    const originalIndex = yield select(selectFilterContextDraggableFilterIndexByRef(filterLocalId));
    yield put(tabsActions.moveAttributeFilter({
        filterLocalId,
        index,
    }));
    const finalIndex = yield select(selectFilterContextDraggableFilterIndexByRef(filterLocalId));
    yield dispatchDashboardEvent(attributeFilterMoved(ctx, affectedFilter, originalIndex, finalIndex, cmd.correlationId));
    yield call(dispatchFilterContextChanged, ctx, cmd);
}
