import { getActiveClient } from '~/client/api/activeClient';
import { createEventSubscriber } from '~/core/events';

/**
 * ```js
 * import { onJoinRequestCreated } from '@amityco/ts-sdk'
 * const dispose = onJoinRequestCreated(data => {
 *   // ...
 * })
 * ```
 *
 * Fired when an {@link Amity.CommunityJoinRequestPayload} has been created
 *
 * @param callback The function to call when the event was fired
 * @returns an {@link Amity.Unsubscriber} function to stop listening
 *
 * @category JoinRequest Events
 */
export const onJoinRequestCreated = (
  callback: Amity.Listener<Amity.InternalJoinRequest[]>,
): Amity.Unsubscriber => {
  const client = getActiveClient();

  const disposers = [
    createEventSubscriber(client, 'onJoinRequestCreated', 'local.joinRequest.created', payload =>
      callback(payload),
    ),
  ];

  return () => {
    disposers.forEach(fn => fn());
  };
};
