import { getActiveClient } from '~/client/api/activeClient';
import { ingestInCache } from '~/cache/api/ingestInCache';
import { fireEvent } from '~/core/events';
import { prepareMembershipPayload } from '~/group/utils';
import { ContentFlagReasonEnum } from '~/@types';

/* begin_public_function
  id: comment.flag
*/
/**
 * ```js
 * import { CommentRepository } from '@amityco/ts-sdk'
 * const flagged = await CommentRepository.flagComment(commentId, reason)
 * ```
 *
 * @param commentId The ID of the comment to flag
 * @param reason the reason to flag the comment
 * @returns the created report result
 *
 * @category Comment API
 * @async
 * */
export const flagComment = async (
  commentId: Amity.Comment['commentId'],
  reason?: Amity.ContentFlagReason,
): Promise<boolean> => {
  const client = getActiveClient();
  client.log('comment/flagComment', commentId);

  const isPredefinedReason =
    reason &&
    Object.entries(ContentFlagReasonEnum).some(
      ([key, value]) => key !== ContentFlagReasonEnum.Others && value === reason,
    );

  const body = {
    reason: reason && isPredefinedReason ? reason : ContentFlagReasonEnum.Others,
    detail: reason && !isPredefinedReason ? reason : '',
  };

  const { data: payload } = await client.http.post<Amity.CommentPayload>(
    `/api/v3/comments/${encodeURIComponent(commentId)}/flag`,
    body,
  );

  if (client.cache) {
    ingestInCache(payload);
  }

  fireEvent('comment.flagged', payload);

  return !!payload;
};
/* end_public_function */
