import { dropFromCache } from '~/cache/api';
import { ENABLE_CACHE_MESSAGE } from '~/utils/constants';
import { getActiveClient } from '~/client/api/activeClient';
import { MyInvitationsLiveCollectionController } from './getMyInvitations/MyInvitationsLiveCollectionController';
import { InvitationStatusEnum } from '~/@types';

/**
 * Get my community invitations
 *
 * @param params the query parameters
 * @param callback the callback to be called when the invitations are fetched
 * @returns invitations
 *
 * @category My Community Invitations Live Collection
 *
 */
export const getMyCommunityInvitations = (
  params: Amity.MyInvitationsLiveCollection,
  callback: Amity.LiveCollectionCallback<Amity.Invitation>,
  config?: Amity.LiveCollectionConfig,
) => {
  const { log, cache } = getActiveClient();

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

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

  const invitationsLiveCollection = new MyInvitationsLiveCollectionController(
    { ...params, targetType: 'community', statuses: [InvitationStatusEnum.Pending] },
    callback,
  );

  const disposers = invitationsLiveCollection.startSubscription();

  const cacheKey = invitationsLiveCollection.getCacheKey();

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

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