// (C) 2019-2026 GoodData Corporation
import { useCallback } from "react";
import { omit } from "lodash-es";
import { isAllValuesAttributeFilter, } from "@gooddata/sdk-model";
import { useCreateAlert } from "./useCreateAlert.js";
import { useUpdateAlert } from "./useUpdateAlert.js";
export function useSaveAlertToBackend({ onCreateSuccess, onCreateError, onUpdateSuccess, onUpdateError, onPauseSuccess, onPauseError, onResumeSuccess, onResumeError, }) {
    const alertCreator = useCreateAlert({
        onSuccess: (alert) => onCreateSuccess?.(alert),
        onError: onCreateError,
    });
    const handleCreateAlert = useCallback((alert) => {
        const sanitizedAlert = sanitizeAutomation(alert);
        alertCreator.create(sanitizedAlert);
    }, [alertCreator]);
    const alertUpdater = useUpdateAlert({
        onSuccess: onUpdateSuccess,
        onError: onUpdateError,
    });
    const handleUpdateAlert = useCallback((alert) => {
        const sanitizedAlert = sanitizeAutomation(alert);
        alertUpdater.save(sanitizedAlert);
    }, [alertUpdater]);
    const alertPauser = useUpdateAlert({
        onSuccess: onPauseSuccess,
        onError: onPauseError,
    });
    const handlePauseAlert = useCallback((alert) => {
        alertPauser.save(sanitizeAutomation(alert));
    }, [alertPauser]);
    const alertResumer = useUpdateAlert({
        onSuccess: onResumeSuccess,
        onError: onResumeError,
    });
    const handleResumeAlert = useCallback((alert) => {
        alertResumer.save(sanitizeAutomation(alert));
    }, [alertResumer]);
    const isSavingAlert = alertCreator.creationStatus === "running" ||
        alertUpdater.savingStatus === "running" ||
        alertPauser.savingStatus === "running" ||
        alertResumer.savingStatus === "running";
    return { handleCreateAlert, handleUpdateAlert, handlePauseAlert, handleResumeAlert, isSavingAlert };
}
function sanitizeAutomation(automationToSave) {
    let automation = {
        ...automationToSave,
    };
    // cronDescription is a variable created on backend that cannot be overridden and BE has hard time
    // handling it with each PUT
    if (automation.schedule) {
        automation.schedule = omit(automation.schedule, ["cronDescription"]);
    }
    if (automation.alert?.execution?.filters) {
        automation = {
            ...automation,
            alert: {
                ...automation.alert,
                execution: {
                    ...automation.alert.execution,
                    filters: removeNoopFiltersFromAlertFilters(automation.alert.execution.filters),
                },
            },
        };
    }
    return automation;
}
function removeNoopFiltersFromAlertFilters(filters) {
    return filters.filter((filter) => !isAllValuesAttributeFilter(filter));
}
