import { dropFromCache } from '~/cache/api/dropFromCache';
import { getActiveClient } from '~/client/api/activeClient';
import { ENABLE_CACHE_MESSAGE } from '~/utils/constants';
import { JoinRequestsLiveCollectionController } from './getJoinRequests/JoinRequestsLiveCollectionController';

/**
 * Get Join Requests
 *
 * @param params the query parameters
 * @param callback the callback to be called when the join request are updated
 * @returns joinRequests
 *
 * @category joinRequest Live Collection
 *
 */
export const getJoinRequests = (
  params: Amity.JoinRequestLiveCollection,
  callback: Amity.LiveCollectionCallback<Amity.JoinRequest>,
  config?: Amity.LiveCollectionConfig,
) => {
  const { log, cache } = getActiveClient();

  if (!cache) {
    console.log(ENABLE_CACHE_MESSAGE);
  }

  const timestamp = Date.now();
  log(`getJoinRequests: (tmpid: ${timestamp}) > listen`);

  const joinRequestLiveCollection = new JoinRequestsLiveCollectionController(params, callback);

  const disposers = joinRequestLiveCollection.startSubscription();

  const cacheKey = joinRequestLiveCollection.getCacheKey();

  disposers.push(() => {
    dropFromCache(cacheKey);
  });

  return () => {
    log(`getJoinRequests (tmpid: ${timestamp}) > dispose`);
    disposers.forEach(fn => fn());
  };
};
