// (C) 2019-2026 GoodData Corporation
import { useCallback, useState } from "react";
import { omit } from "lodash-es";
import { useIntl } from "react-intl";
import { isAllValuesAttributeFilter, isAllValuesDashboardAttributeFilter, isExportDefinitionDashboardRequestPayload, isExportDefinitionVisualizationObjectRequestPayload, isNoopAllTimeDashboardDateFilter, isNoopAllTimeDateFilter, } from "@gooddata/sdk-model";
import { useDashboardSelector } from "../../../../model/react/DashboardStoreProvider.js";
import { selectEnableAutomationFilterContext } from "../../../../model/store/config/configSelectors.js";
import { useCreateScheduledEmail } from "./useCreateScheduledEmail.js";
import { useUpdateScheduledEmail } from "./useUpdateScheduledEmail.js";
export function useSaveScheduledEmailToBackend(automation, { onSuccess, onError, onSubmit, onSaveSuccess, onSaveError, onSave, }) {
    const intl = useIntl();
    const enableAutomationFilterContext = useDashboardSelector(selectEnableAutomationFilterContext);
    const [savingErrorMessage, setSavingErrorMessage] = useState(undefined);
    const scheduledEmailCreator = useCreateScheduledEmail({
        onSuccess: (scheduledEmail) => {
            onSuccess?.(scheduledEmail);
        },
        onError: (error) => {
            /**
             * Handle 400 error separately as it contains a detailed error message
             * to be shown in the dialog without closing it
             */
            if (error?.cause?.response?.status === 400) {
                setSavingErrorMessage(error.cause.response.data?.detail);
            }
            else {
                onError?.(error);
            }
        },
        onBeforeRun: (scheduledEmailToCreate) => {
            setSavingErrorMessage(undefined);
            onSubmit?.(scheduledEmailToCreate);
        },
    });
    const handleCreateScheduledEmail = useCallback((scheduledEmail) => {
        const sanitizedAutomation = sanitizeAutomation(scheduledEmail, intl, enableAutomationFilterContext);
        scheduledEmailCreator.create(sanitizedAutomation);
    }, [scheduledEmailCreator, enableAutomationFilterContext, intl]);
    const scheduledEmailUpdater = useUpdateScheduledEmail({
        onSuccess: onSaveSuccess,
        onError: (error) => {
            /**
             * Handle 400 error separately as it contains a detailed error message
             * to be shown in the dialog without closing it
             */
            if (error?.cause?.response?.status === 400) {
                setSavingErrorMessage(error.cause.response.data?.detail);
            }
            else {
                onSaveError?.(error);
            }
        },
        onBeforeRun: (scheduledEmailToSave) => {
            setSavingErrorMessage(undefined);
            onSave?.(scheduledEmailToSave);
        },
    });
    const handleUpdateScheduledEmail = useCallback((scheduledEmail) => {
        const sanitizedAutomation = sanitizeAutomation(scheduledEmail, intl, enableAutomationFilterContext);
        scheduledEmailUpdater.save(sanitizedAutomation);
    }, [scheduledEmailUpdater, enableAutomationFilterContext, intl]);
    const handleSaveScheduledEmail = () => {
        const sanitizedAutomation = sanitizeAutomation(automation, intl, enableAutomationFilterContext);
        if (sanitizedAutomation.id) {
            handleUpdateScheduledEmail(sanitizedAutomation);
        }
        else {
            handleCreateScheduledEmail(sanitizedAutomation);
        }
    };
    const isSavingScheduledEmail = scheduledEmailCreator.creationStatus === "running" ||
        scheduledEmailUpdater.savingStatus === "running";
    return { handleSaveScheduledEmail, isSavingScheduledEmail, savingErrorMessage };
}
function sanitizeAutomation(automationToSave, intl, enableAutomationFilterContext) {
    const automation = {
        ...automationToSave,
    };
    if (!automation.title) {
        automation.title = intl.formatMessage({ id: "dialogs.schedule.email.title.placeholder" });
    }
    // We want to omit the cronDescription as it is a variable created on backend that cannot
    // be overriden and BE has hard time handling it with each PUT
    if (automation.schedule) {
        automation.schedule = omit(automation.schedule, ["cronDescription"]);
    }
    /**
     * Remove noop filters from export definitions before saving to backend.
     * - "All time" date filters are not required for the execution and not even valid as AFM date granularity.
     *   They are added ad-hoc to be visible in the UI in useAutomationFiltersSelect hook,
     *   depending on whether they are ignored or not.
     * - "All values" attribute filters have no effect on execution and should not appear in notifications.
     */
    if (automation.exportDefinitions) {
        automation.exportDefinitions = removeNoopFiltersFromExportDefinitions(automation.exportDefinitions, enableAutomationFilterContext);
    }
    return automation;
}
function removeNoopFiltersFromExportDefinitions(exportDefinitions, enableAutomationFilterContext) {
    return exportDefinitions.map((exportDefinition) => {
        if (isExportDefinitionVisualizationObjectRequestPayload(exportDefinition.requestPayload)) {
            const filters = exportDefinition.requestPayload.content.filters;
            const format = exportDefinition.requestPayload.format;
            const isTabularFormat = format === "XLSX" || format === "CSV";
            return {
                ...exportDefinition,
                requestPayload: {
                    ...exportDefinition.requestPayload,
                    content: {
                        ...exportDefinition.requestPayload.content,
                        filters: filters?.filter((filter) => {
                            // Strip noop "All values" attribute filters (handles both IFilter and FilterContextItem formats).
                            if (isAllValuesAttributeFilter(filter) ||
                                isAllValuesDashboardAttributeFilter(filter)) {
                                return false;
                            }
                            // Strip noop "All time" date filters only for legacy path.
                            if (!enableAutomationFilterContext) {
                                return isTabularFormat
                                    ? !isNoopAllTimeDateFilter(filter)
                                    : !isNoopAllTimeDashboardDateFilter(filter);
                            }
                            return true;
                        }),
                    },
                },
            };
        }
        else if (isExportDefinitionDashboardRequestPayload(exportDefinition.requestPayload)) {
            return {
                ...exportDefinition,
                requestPayload: {
                    ...exportDefinition.requestPayload,
                    content: {
                        ...exportDefinition.requestPayload.content,
                        filters: exportDefinition.requestPayload.content.filters?.filter((filter) => {
                            // Strip noop "All values" attribute filters.
                            if (isAllValuesDashboardAttributeFilter(filter)) {
                                return false;
                            }
                            // Strip noop "All time" date filters only for legacy path.
                            if (!enableAutomationFilterContext && isNoopAllTimeDashboardDateFilter(filter)) {
                                return false;
                            }
                            return true;
                        }),
                    },
                },
            };
        }
        return exportDefinition;
    });
}
//# sourceMappingURL=useSaveScheduledEmailToBackend.js.map