import { useState } from 'react';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { getGlobalSettings, setGlobalSettings, } from '@wix/bex-utils/@wix/ambassador-app-settings-v1-settings/http';
import { Host } from '@wix/bex-utils/@wix/ambassador-app-settings-v1-settings/types';
export function useFixMissingContactsViews(collectionState) {
    const { errorMonitor, httpClient } = useWixPatternsContainer();
    useState(() => {
        const oldContactsPageId = 'contacts-page-component';
        collectionState._fixMissingContactsViews = async (state) => {
            const { viewsService } = state;
            const { viewsStorage, fqdn } = viewsService;
            try {
                const { data } = await httpClient.request(getGlobalSettings({
                    host: Host.BUSINESS_MANAGER,
                }));
                const isMigrated = !!data?.settings?.[oldContactsPageId]?._migrationDate;
                if (isMigrated) {
                    return;
                }
                const oldViews = data?.settings?.[oldContactsPageId]?.cairo?.[fqdn];
                // no views from old contacts views app-settings
                if (oldViews == null || !oldViews?.views?.list) {
                    return;
                }
                const newViews = await viewsStorage.getItem(fqdn);
                const newViewsList = newViews?.views?.list || {};
                const oldViewsList = oldViews?.views?.list;
                const newViewNames = new Set(Object.values(newViewsList)
                    .map((view) => view?.name)
                    .filter((n) => n));
                Object.values(oldViewsList).forEach((oldView) => {
                    if (oldView?.id && !newViewNames.has(oldView?.name)) {
                        newViewsList[oldView?.id] = oldView;
                    }
                });
                if (Object.keys(newViewsList).length > 0) {
                    await Promise.all([
                        viewsStorage.setItem(fqdn, { views: { list: newViewsList } }),
                        httpClient.request(setGlobalSettings({
                            host: Host.BUSINESS_MANAGER,
                            settings: {
                                [oldContactsPageId]: {
                                    _migrationDate: new Date(),
                                },
                            },
                        })),
                    ]);
                }
            }
            catch (e) {
                errorMonitor.captureException(e);
            }
        };
    });
}
//# sourceMappingURL=useFixMissingContactsViews.js.map