// (C) 2021-2026 GoodData Corporation
import { call, select } from "redux-saga/effects";
import { defWithDimensions, defaultDimensionsGenerator, idRef, insightRef, insightSetFilters, isObjRef, isWidget, newDefForInsight, } from "@gooddata/sdk-model";
import { fillMissingTitles, resolveDefaultDisplayFormRefForDisplayForm, resolveMessages, } from "@gooddata/sdk-ui";
import { scheduledEmailSaved } from "../../events/scheduledEmail.js";
import { queryWithInsight } from "../../queryServices/queryWidgetFilters.js";
import { selectCatalogAttributes } from "../../store/catalog/catalogSelectors.js";
import { selectLocale, selectSettings } from "../../store/config/configSelectors.js";
import { selectExecutionResultByRef } from "../../store/executionResults/executionResultsSelectors.js";
import { selectAutomationCommonDateFilterId } from "../../store/filtering/dashboardFilterSelectors.js";
import { selectInsightByRef, selectInsightByWidgetRef, selectRawExportOverridesForInsight, } from "../../store/insights/insightsSelectors.js";
import { selectPreloadedAttributesWithReferences } from "../../store/tabs/filterContext/filterContextSelectors.js";
import { selectWidgetByRef } from "../../store/tabs/layout/layoutSelectors.js";
import { prepareGeoRawExportDefinition } from "../common/prepareGeoRawExportDefinition.js";
import { prepareCsvRawExecutionDefinition } from "./csvRawExecutionDefinition.js";
function saveScheduledEmail(ctx, scheduledEmail, preparedExecutionDefinition, overrides) {
    const { backend, workspace } = ctx;
    if (!isObjRef(scheduledEmail)) {
        throw new Error("Cannot save schedule not referencing to an persisted object");
    }
    return backend
        .workspace(workspace)
        .automations()
        .updateAutomation(scheduledEmail, undefined, preparedExecutionDefinition, overrides);
}
export function* saveScheduledEmailHandler(ctx, cmd) {
    const scheduledEmail = cmd.payload.scheduledEmail;
    const csvRawRequest = scheduledEmail.exportDefinitions?.find((def) => def.requestPayload.format === "CSV_RAW")?.requestPayload;
    const widgetId = csvRawRequest?.content?.widget;
    const ref = widgetId ? idRef(widgetId) : undefined;
    const executionEnvelope = yield select(selectExecutionResultByRef(ref));
    let preparedExecutionDefinition = executionEnvelope?.executionResult?.definition;
    const widget = yield select(selectWidgetByRef(ref));
    const commonDateFilterId = yield select(selectAutomationCommonDateFilterId);
    const insight = yield select(selectInsightByWidgetRef(ref));
    const locale = yield select(selectLocale);
    const messages = yield call(resolveMessages, locale);
    const lookupInsight = insight ? yield select(selectInsightByRef(insightRef(insight))) : undefined;
    const filledInsight = lookupInsight
        ? yield call(fillMissingTitles, lookupInsight, locale, messages)
        : undefined;
    // Build execution definition from insight when execution result is unavailable
    // (e.g., when widget shows "no data"). Uses the same filter resolution as widget rendering.
    if (!preparedExecutionDefinition && csvRawRequest && widgetId && lookupInsight && isWidget(widget)) {
        const resolvedFilters = yield call(queryWithInsight, ctx, widget, lookupInsight);
        const insightWithResolvedFilters = insightSetFilters(lookupInsight, resolvedFilters);
        preparedExecutionDefinition = defWithDimensions(newDefForInsight(ctx.workspace, insightWithResolvedFilters), defaultDimensionsGenerator);
    }
    if (csvRawRequest && widgetId) {
        if (!preparedExecutionDefinition) {
            throw new Error("CSV raw widget attachment requires an available execution.");
        }
        if (!widget) {
            throw new Error("CSV raw widget attachment requires an available widget.");
        }
    }
    const preparedExecutionDefinitionWithFilters = prepareCsvRawExecutionDefinition(preparedExecutionDefinition, csvRawRequest, insight, widget, commonDateFilterId);
    const settings = yield select(selectSettings);
    const catalogAttributes = yield select(selectCatalogAttributes);
    const preloadedAttributesWithReferences = yield select(selectPreloadedAttributesWithReferences);
    const preparedGeoRawExport = lookupInsight && filledInsight && preparedExecutionDefinitionWithFilters
        ? prepareGeoRawExportDefinition({
            baseExecutionDefinition: preparedExecutionDefinitionWithFilters,
            sourceInsight: lookupInsight,
            filledInsight,
            workspace: ctx.workspace,
            settings,
            resolveDefaultDisplayFormRef: (displayFormRef) => resolveDefaultDisplayFormRefForDisplayForm(displayFormRef, catalogAttributes, preloadedAttributesWithReferences),
        })
        : undefined;
    const overridesInsight = preparedGeoRawExport?.filledInsight ?? filledInsight;
    const overrides = overridesInsight
        ? yield select(selectRawExportOverridesForInsight(overridesInsight))
        : undefined;
    yield call(saveScheduledEmail, ctx, scheduledEmail, preparedGeoRawExport?.executionDefinition ?? preparedExecutionDefinitionWithFilters, overrides);
    return scheduledEmailSaved(ctx, cmd.correlationId);
}
//# sourceMappingURL=saveScheduledEmailHandler.js.map