// (C) 2025-2026 GoodData Corporation
import { call, put, select } from "redux-saga/effects";
import { v4 as uuid } from "uuid";
import { createDefaultFilterContext } from "../../../_staging/dashboard/defaultFilterContext.js";
import { DEFAULT_FISCAL_DATE_FILTER_PRESET } from "../../../_staging/dateFilterConfig/defaultConfig.js";
import { configHasFiscalPresets } from "../../../_staging/dateFilterConfig/validation.js";
import { switchDashboardTab } from "../../commands/tabs.js";
import { dashboardTabCreated } from "../../events/tabs.js";
import { dispatchDashboardEvent } from "../../store/_infra/eventDispatcher.js";
import { InitialUndoState } from "../../store/_infra/undoEnhancer.js";
import { selectActiveCalendars, selectDateFilterConfig } from "../../store/config/configSelectors.js";
import { tabsActions } from "../../store/tabs/index.js";
import { selectScreen } from "../../store/tabs/layout/layoutSelectors.js";
import { selectActiveTabLocalIdentifier, selectTabs } from "../../store/tabs/tabsSelectors.js";
import { EmptyDashboardLayout } from "../dashboard/common/dashboardInitialize.js";
import { switchDashboardTabHandler } from "./switchDashboardTabHandler.js";
const getTabState = ({ title, localIdentifier, isRenaming, filterContext, dateFilterConfig, dateFilterConfigs, attributeFilterConfigs, layout, screen, }) => {
    return {
        title,
        localIdentifier,
        isRenaming,
        filterContext: {
            filtersWithInvalidSelection: [],
            filterContextDefinition: filterContext,
        },
        dateFilterConfig: {
            dateFilterConfig: undefined,
            effectiveDateFilterConfig: dateFilterConfig,
            isUsingDashboardOverrides: false,
            dateFilterConfigValidationWarnings: undefined,
        },
        dateFilterConfigs: {
            dateFilterConfigs,
        },
        attributeFilterConfigs: {
            attributeFilterConfigs,
        },
        layout: {
            layout: layout,
            stash: {},
            screen,
            ...InitialUndoState,
        },
    };
};
/**
 * @internal
 */
export function* createDashboardTabHandler(ctx, cmd) {
    const { title = "", index, shouldStartRenaming = true } = cmd.payload;
    // 1. Get current state from main dashboard slices
    const tabs = yield select(selectTabs);
    const activeTabLocalIdentifier = yield select(selectActiveTabLocalIdentifier);
    const dateFilterConfig = yield select(selectDateFilterConfig);
    const activeCalendars = yield select(selectActiveCalendars);
    const screen = yield select(selectScreen);
    const updatedTabs = (tabs ?? []).slice();
    // 2. Create new tab with an empty filter context and layout
    const effectiveDateFilterConfig = activeCalendars?.fiscal &&
        activeCalendars?.default === "FISCAL" &&
        configHasFiscalPresets(dateFilterConfig)
        ? { ...dateFilterConfig, selectedOption: DEFAULT_FISCAL_DATE_FILTER_PRESET }
        : dateFilterConfig;
    const newTabId = uuid();
    const newTabFilterContext = createDefaultFilterContext(effectiveDateFilterConfig, true);
    const newTab = getTabState({
        localIdentifier: newTabId,
        title,
        layout: EmptyDashboardLayout,
        screen,
        filterContext: newTabFilterContext,
        dateFilterConfig,
        isRenaming: shouldStartRenaming,
    });
    // 4. Insert new tab at specified index (or append)
    const insertionIndex = Math.max(0, Math.min(typeof index === "number" && Number.isInteger(index) ? index : updatedTabs.length, updatedTabs.length));
    updatedTabs.splice(insertionIndex, 0, newTab);
    // 5. Persist tabs with current active id, the new tab will be switched to later
    yield put(tabsActions.setTabs({
        tabs: updatedTabs,
        activeTabLocalIdentifier,
    }));
    // 6. Emit created event
    yield dispatchDashboardEvent(dashboardTabCreated(ctx, newTabId, insertionIndex, cmd.correlationId));
    // 7. Switch to the newly created tab
    const switchedEvent = yield call(switchDashboardTabHandler, ctx, switchDashboardTab(newTabId, cmd.correlationId));
    // Important: explicitly dispatch the switched event so app-level sagas can sync URL
    yield dispatchDashboardEvent(switchedEvent);
}
//# sourceMappingURL=createDashboardTabHandler.js.map