// (C) 2021-2026 GoodData Corporation
import { batchActions } from "redux-batched-actions";
import { all, call, put, select } from "redux-saga/effects";
import { convertError } from "@gooddata/sdk-ui";
import { automationsRefreshed } from "../../events/scheduledEmail.js";
import { automationsActions } from "../../store/automations/index.js";
import { selectEnableAlerting, selectEnableScheduling, selectExternalRecipient, selectIsReadOnly, } from "../../store/config/configSelectors.js";
import { selectDashboardId } from "../../store/meta/metaSelectors.js";
import { selectCanManageWorkspace } from "../../store/permissions/permissionsSelectors.js";
import { selectCurrentUser } from "../../store/user/userSelectors.js";
import { loadDashboardUserAutomations, loadWorkspaceAutomationsCount } from "./loadAutomations.js";
export function* refreshAutomationsHandlers(ctx, cmd) {
    const dashboardId = yield select(selectDashboardId);
    const user = yield select(selectCurrentUser);
    const enableScheduling = yield select(selectEnableScheduling);
    const enableAlerting = yield select(selectEnableAlerting);
    const canManageAutomations = yield select(selectCanManageWorkspace);
    const isReadOnly = yield select(selectIsReadOnly);
    const enableAutomations = enableScheduling || enableAlerting;
    const externalRecipient = yield select(selectExternalRecipient);
    if (!dashboardId || !user || !enableAutomations || isReadOnly) {
        return;
    }
    yield put(automationsActions.setAutomationsLoading(true));
    try {
        const [automations, allAutomationsCount] = yield all([
            call(loadDashboardUserAutomations, ctx, dashboardId, user.login, !canManageAutomations, externalRecipient),
            call(loadWorkspaceAutomationsCount, ctx),
        ]);
        yield put(batchActions([
            automationsActions.setAutomationsLoading(false),
            automationsActions.setUserAutomations(automations),
            automationsActions.setAllAutomationsCount(allAutomationsCount),
        ]));
    }
    catch (e) {
        yield put(automationsActions.setAutomationsLoading(false));
        batchActions([
            automationsActions.setAutomationsLoading(false),
            automationsActions.setAutomationsError(convertError(e)),
        ]);
    }
    return automationsRefreshed(ctx, cmd.correlationId);
}
