"use strict";

exports.__esModule = true;
exports.useMigrateOrdersViews = useMigrateOrdersViews;
var _react = require("react");
var _react2 = require("@wix/bex-core/react");
var _http = require("@wix/bex-utils/@wix/ambassador-app-settings-v1-settings/http");
var _types = require("@wix/bex-utils/@wix/ambassador-app-settings-v1-settings/types");
function useMigrateOrdersViews(collectionState) {
  const {
    errorMonitor,
    httpClient
  } = (0, _react2.useWixPatternsContainer)();
  (0, _react.useState)(() => {
    const ordersViewSettingsKey = 'orders.views';
    collectionState._migrateOrdersViews = async state => {
      const {
        viewsService
      } = state;
      const {
        viewsStorage,
        fqdn
      } = viewsService;
      try {
        var _data$settings;
        const {
          data
        } = await httpClient.request((0, _http.getGlobalSettings)({
          host: _types.Host.BUSINESS_MANAGER
        }));
        const legacyViews = data == null || (_data$settings = data.settings) == null ? void 0 : _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 == null ? void 0 : viewsDiff.reduce((list, view, index) => {
              list[view.id] = {
                ...view,
                createdAt: new Date(now - index).toISOString()
              };
              return list;
            }, {}),
            hiddenPresetIds: hiddenPresetIdsDiff == null ? void 0 : hiddenPresetIdsDiff.reduce((hiddenPresetIds, id) => {
              hiddenPresetIds[id] = id;
              return hiddenPresetIds;
            }, {})
          }
        };
        await Promise.all([viewsStorage.setItem(fqdn, mergedViews), httpClient.request((0, _http.setGlobalSettings)({
          host: _types.Host.BUSINESS_MANAGER,
          settings: {
            [ordersViewSettingsKey]: {
              _migrationDate: new Date()
            }
          }
        }))]);
      } catch (e) {
        errorMonitor.captureException(e);
      }
    };
  });
}
//# sourceMappingURL=useMigrateOrdersViews.js.map