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 useMigrateOrdersViews(collectionState) {
    const { errorMonitor, httpClient } = useWixPatternsContainer();
    useState(() => {
        const ordersViewSettingsKey = 'orders.views';
        collectionState._migrateOrdersViews =
            async (state) => {
                const { viewsService } = state;
                const { viewsStorage, fqdn } = viewsService;
                try {
                    const { data } = await httpClient.request(getGlobalSettings({
                        host: Host.BUSINESS_MANAGER,
                    }));
                    const legacyViews = data?.settings?.[ordersViewSettingsKey];
                    // no views from old orders views app-settings
                    if (legacyViews == null) {
                        return;
                    }
                    // already migrated
                    if (legacyViews._migrationDate) {
                        return;
                    }
                    const viewsDiff = legacyViews.views;
                    const hiddenPresetIdsDiff = legacyViews.hiddenPresetIds;
                    const now = Date.now();
                    const mergedViews = {
                        views: {
                            list: viewsDiff?.reduce((list, view, index) => {
                                list[view.id] = {
                                    ...view,
                                    createdAt: new Date(now - index).toISOString(),
                                };
                                return list;
                            }, {}),
                            hiddenPresetIds: hiddenPresetIdsDiff?.reduce((hiddenPresetIds, id) => {
                                hiddenPresetIds[id] = id;
                                return hiddenPresetIds;
                            }, {}),
                        },
                    };
                    await Promise.all([
                        viewsStorage.setItem(fqdn, mergedViews),
                        httpClient.request(setGlobalSettings({
                            host: Host.BUSINESS_MANAGER,
                            settings: {
                                [ordersViewSettingsKey]: {
                                    _migrationDate: new Date(),
                                },
                            },
                        })),
                    ]);
                }
                catch (e) {
                    errorMonitor.captureException(e);
                }
            };
    });
}
//# sourceMappingURL=useMigrateOrdersViews.js.map