"use strict";

exports.__esModule = true;
exports.useItemsSelectionFilter = void 0;
var _http = require("@wix/bex-utils/@wix/ambassador-items-selection-spi-host-v1-provider/http");
var _react = require("@wix/bex-core/react");
var _useFilterCollection = require("../useFilterCollection");
function buildRequest(params) {
  const {
    query,
    providerKey
  } = params;
  const resolvedQuery = query.cursor != null ? {
    cursorPaging: {
      cursor: query.cursor,
      limit: query.limit
    }
  } : query.offset != null && query.offset > 0 ? {
    paging: {
      offset: query.offset,
      limit: query.limit
    }
  } : {
    paging: {
      limit: query.limit,
      offset: 0
    },
    cursorPaging: {
      limit: query.limit
    }
  };
  if (!query.cursor) {
    if (query.filters && Object.keys(query.filters).length > 0) {
      resolvedQuery.filter = {
        ...query.filters
      };
    }

    // According to the guidelines, we should not pass search query if cursor is present
    if (query.search) {
      resolvedQuery.search = query.search;
    }
  }
  const request = {
    providerKey,
    query: resolvedQuery
  };
  return request;
}

// When we publish items-selection-code, we need to use this code from there and no to duplicate it here
const useQueryItems = () => {
  const {
    httpClient,
    errorHandler: {
      withErrorHandler
    },
    translate: t
  } = (0, _react.useWixPatternsContainer)();
  const fetchItems = async ({
    providerKey,
    query
  }) => {
    var _pagingMetadata$curso;
    const request = buildRequest({
      query,
      providerKey
    });
    const res = await withErrorHandler(() => httpClient.request((0, _http.queryItems)(request)), {
      PROVIDER_NOT_FOUND: () => ({
        message: t('cairo.provider-not-found.error'),
        action: {
          text: t('cairo.error.contactSupport.cta'),
          onClick: () => {}
        }
      }),
      QUERY_PROVIDER_ITEMS_FAILED: () => ({
        message: t('cairo.provider-not-found.error'),
        action: {
          text: t('cairo.error.contactSupport.cta'),
          onClick: () => {}
        }
      })
    });
    const {
      items,
      pagingMetadata
    } = res.data;
    return {
      items: items || [],
      total: (pagingMetadata == null ? void 0 : pagingMetadata.total) || 0,
      hasNext: pagingMetadata == null ? void 0 : pagingMetadata.hasNext,
      cursor: pagingMetadata == null || (_pagingMetadata$curso = pagingMetadata.cursors) == null ? void 0 : _pagingMetadata$curso.next
    };
  };
  return {
    fetchItems
  };
};
const useItemsSelectionFilter = ({
  providerKey,
  filter,
  queryFilters
}) => {
  const {
    httpClient
  } = (0, _react.useWixPatternsContainer)();
  const {
    fetchItems
  } = useQueryItems();
  const renderItem = item => ({
    title: (item == null ? void 0 : item.name) ?? '',
    subtitle: (item == null ? void 0 : item.description) ?? ''
  });
  const collection = (0, _useFilterCollection.useFilterCollection)(filter, {
    queryName: providerKey,
    fetchData: async query => {
      const {
        items,
        ...res
      } = await fetchItems({
        providerKey,
        query: {
          ...query,
          filters: {
            ...(queryFilters || {}),
            ...query.filters
          }
        },
        httpClient
      });

      // initial pagination unknown, set to cursor if next cursor exists
      collection._paginationModeRef.current = res.cursor ? 'cursor' : 'offset';
      return {
        ...res,
        items
      };
    },
    limit: 50
  });
  return {
    collection,
    renderItem
  };
};
exports.useItemsSelectionFilter = useItemsSelectionFilter;
//# sourceMappingURL=useItemsSelectionFilter.js.map