// (C) 2021-2026 GoodData Corporation
import { call, select } from "redux-saga/effects";
import { defWithDimensions, defaultDimensionsGenerator, idRef, insightRef, insightSetFilters, isWidget, newDefForInsight, } from "@gooddata/sdk-model";
import { fillMissingTitles, resolveDefaultDisplayFormRefForDisplayForm, resolveMessages, } from "@gooddata/sdk-ui";
import { scheduledEmailCreated } 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 { selectReferencedInsightParameterValuesForWidget } from "../../store/tabs/parameters/parametersSelectors.js";
import { prepareGeoRawExportDefinition } from "../common/prepareGeoRawExportDefinition.js";
import { prepareCsvRawExecutionDefinition } from "./csvRawExecutionDefinition.js";
function createScheduledEmail(ctx, scheduledEmail, preparedExecutionDefinition, overrides) {
    const { backend, workspace } = ctx;
    return backend
        .workspace(workspace)
        .automations()
        .createAutomation(scheduledEmail, undefined, preparedExecutionDefinition, overrides);
}
export function* createScheduledEmailHandler(ctx, cmd) {
    const csvRawRequest = cmd.payload.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 insightParameterValues = yield select(selectReferencedInsightParameterValuesForWidget(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, insightParameterValues, 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;
    const scheduledEmail = yield call(createScheduledEmail, ctx, cmd.payload.scheduledEmail, preparedGeoRawExport?.executionDefinition ?? preparedExecutionDefinitionWithFilters, overrides);
    return scheduledEmailCreated(ctx, scheduledEmail, cmd.correlationId);
}
