import { getActiveClient } from '~/client/api/activeClient';
import { ingestInCache } from '~/cache/api/ingestInCache';
import { prepareCommunityJoinRequestPayload } from '~/communityRepository/utils';
import { joinRequestLinkedObject } from '~/utils/linkedObject/joinRequestLinkedObject';

/* begin_public_function
  id: community.getMyJoinRequest
*/
/**
 * ```js
 * import { community } from '@amityco/ts-sdk'
 * const isJoined = await community.getMyJoinRequest('foobar')
 * ```
 *
 * Joins a {@link Amity.Community} object
 *
 * @param communityId the {@link Amity.Community} to join
 * @returns A success boolean if the {@link Amity.Community} was joined
 *
 * @category Community API
 * @async
 */
export const getMyJoinRequest = async (
  communityId: Amity.Community['communityId'],
): Promise<Amity.Cached<Amity.JoinRequest | undefined>> => {
  const client = getActiveClient();
  client.log('community/myJoinRequest', communityId);

  const { data: payload } = await client.http.get<Amity.CommunityJoinRequestPayload>(
    `/api/v4/communities/${communityId}/join/me`,
  );

  const data = prepareCommunityJoinRequestPayload(payload);

  const cachedAt = client.cache && Date.now();
  if (client.cache) ingestInCache(data, { cachedAt });

  return {
    data: data.joinRequests[0] ? joinRequestLinkedObject(data.joinRequests[0]) : undefined,
    cachedAt,
  };
};
/* end_public_function */
