// (C) 2024-2026 GoodData Corporation
import { useMemo } from "react";
import { defineMessages, useIntl } from "react-intl";
import { layoutWidgets } from "@gooddata/sdk-backend-spi";
import { areObjRefsEqual, filterLocalIdentifier, filterObjRef, idRef, isAttributeFilter, isDateFilter, isPositiveAttributeFilter, } from "@gooddata/sdk-model";
import { useBackendStrict, useCancelablePromise } from "@gooddata/sdk-ui";
import { translateAttributeFilter } from "./attributeFilterNaming.js";
import { translateDateFilter } from "./dateFilterNaming.js";
const messages = defineMessages({
    title: {
        id: "notifications.filters.dialog.title",
    },
    dateRange: {
        id: "notifications.filters.dialog.dateRange",
    },
});
function getObjRefInScopeLocalId(attributeFilter) {
    if (isPositiveAttributeFilter(attributeFilter)) {
        return attributeFilter.positiveAttributeFilter.displayForm.localIdentifier;
    }
    return attributeFilter.negativeAttributeFilter.displayForm.localIdentifier;
}
function fetchAutomation(backend, workspaceId, automationId) {
    return backend.workspace(workspaceId).automations().getAutomation(automationId);
}
function fetchDashboard(backend, workspaceId, dashboardId) {
    return backend.workspace(workspaceId).dashboards().getDashboardWithReferences(idRef(dashboardId));
}
function fetchLabels(backend, workspaceId, filterDisplayFormsRefs) {
    return backend.workspace(workspaceId).attributes().getAttributeDisplayForms(filterDisplayFormsRefs);
}
export function useNotificationsFilterDetail(notification) {
    const backend = useBackendStrict(undefined, "NotificationTriggerDetails");
    const intl = useIntl();
    const automationPromise = useCancelablePromise({
        promise: async () => {
            if (!notification.automationId || !notification.workspaceId) {
                return null;
            }
            const automation = await fetchAutomation(backend, notification.workspaceId, notification.automationId);
            const automationAlert = automation?.alert;
            if (!automationAlert) {
                return null;
            }
            const filterDisplayFormsRefs = automationAlert.execution.filters
                .filter((f) => isAttributeFilter(f))
                .map((filter) => {
                const ref = filterObjRef(filter);
                if (!ref) {
                    const attribute = automationAlert.execution.attributes.find((a) => a.attribute.localIdentifier === getObjRefInScopeLocalId(filter));
                    if (!attribute) {
                        return null;
                    }
                    return attribute.attribute.displayForm;
                }
                return filterObjRef(filter);
            })
                .filter(Boolean);
            const dashboardId = automation?.dashboard?.id;
            const dashboardPromise = dashboardId
                ? fetchDashboard(backend, notification.workspaceId, dashboardId)
                : Promise.resolve(null);
            const labelsPromise = fetchLabels(backend, notification.workspaceId, filterDisplayFormsRefs);
            const [dashboard, labels] = await Promise.all([dashboardPromise, labelsPromise]);
            return { automation, dashboard, labels };
        },
    }, [notification.automationId, notification.workspaceId]);
    const filtersInfo = useMemo(() => {
        if (!automationPromise.result) {
            return null;
        }
        const { automation, dashboard, labels } = automationPromise.result;
        const alert = automation?.alert;
        if (!alert) {
            return [];
        }
        const widgets = dashboard?.dashboard.layout ? layoutWidgets(dashboard.dashboard.layout) : [];
        const widget = widgets.find((w) => w.identifier === automation.metadata?.widget);
        const insight = dashboard?.references.insights.find((i) => i.insight.identifier === widget.insight.identifier);
        const filtersWithoutInsightFilters = alert.execution.filters.filter((f) => {
            const insightFilter = insight?.insight.filters.find((f2) => {
                return filterLocalIdentifier(f) === filterLocalIdentifier(f2);
            });
            return !insightFilter;
        });
        return filtersWithoutInsightFilters
            .map((filter) => {
            let ref = filterObjRef(filter);
            let subtitle = "";
            let title = "";
            if (isAttributeFilter(filter)) {
                const attribute = alert.execution.attributes.find((a) => a.attribute.localIdentifier === getObjRefInScopeLocalId(filter));
                if (attribute) {
                    ref = attribute.attribute.displayForm;
                }
                subtitle = translateAttributeFilter(intl, filter);
                title = labels.find((l) => areObjRefsEqual(l.ref, ref))?.title ?? "";
            }
            else if (isDateFilter(filter)) {
                subtitle = translateDateFilter(intl, filter, "MM/dd/yyyy");
                title = intl.formatMessage(messages.dateRange);
            }
            else {
                return null;
            }
            return { title, subtitle };
        })
            .filter(Boolean);
    }, [automationPromise.result, intl]);
    return { filtersInfo, automationPromise };
}
//# sourceMappingURL=useNotificationFiltersDetail.js.map