import { useCallback, useState } from 'react';
import { identity } from 'ramda';
import { isDataTenantEntity, mergeCustomerTenantEntityWithMixedEntities, mergeDataTenantEntity } from '@reltio/mdm-sdk';
import { useIsMountedRef } from '../useIsMountedRef';
import { getWinnerLosersUrisFromMergeResponses } from './helpers';
import { useMdmAction, useMdmDtssPath, useMdmTenant } from '../../contexts/MdmModuleContext';
export var useMergeAllRequest = function (_a) {
    var entities = _a.entities, entity = _a.entity, onFinishRequest = _a.onFinishRequest, onStartRequest = _a.onStartRequest, onSuccess = _a.onSuccess, _b = _a.onError, onError = _b === void 0 ? identity : _b;
    var isMountedRef = useIsMountedRef();
    var _c = useState(false), isPending = _c[0], setIsPending = _c[1];
    var updateSearchNavigationDataOnMerge = useMdmAction('updateSearchNavigationDataOnMerge');
    var tenant = useMdmTenant();
    var dtssPath = useMdmDtssPath();
    var sendMergeAllRequest = useCallback(function () {
        onStartRequest === null || onStartRequest === void 0 ? void 0 : onStartRequest();
        setIsPending(true);
        var params = { dtssPath: dtssPath, customerTenant: tenant, entity: entity, entities: entities };
        (isDataTenantEntity(entity)
            ? mergeDataTenantEntity(params)
            : mergeCustomerTenantEntityWithMixedEntities(params))
            .then(function (responses) {
            onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess();
            var uris = getWinnerLosersUrisFromMergeResponses(entity, entities, responses);
            if (uris) {
                var winnerUri = uris.winnerUri, losersUris = uris.losersUris;
                updateSearchNavigationDataOnMerge({ winnerUri: winnerUri, losersUris: losersUris });
            }
        })
            .catch(onError)
            .finally(function () {
            onFinishRequest === null || onFinishRequest === void 0 ? void 0 : onFinishRequest();
            if (isMountedRef.current)
                setIsPending(false);
        });
    }, [
        dtssPath,
        entities,
        entity,
        onError,
        onFinishRequest,
        onStartRequest,
        onSuccess,
        tenant,
        updateSearchNavigationDataOnMerge
    ]);
    return { isPending: isPending, sendMergeAllRequest: sendMergeAllRequest };
};
