import lodash from 'lodash';
import { parseBody } from '@/lib/utils/utils';
import { storageBadWord } from '@/plugins/storage/items';

export const shopeeBadWord = {
  listBadWord: [],

  /**
   * @param {string[]} push
   */
  pushList(push = []) {
    this.listBadWord.push(...push);
  },

  /**
   * @returns {string[]}
   */
  getList() {
    return this.listBadWord;
  },

  /**
   * @returns {Promise<string[]>}
   */
  async fetchList() {
    this.listBadWord = await storageBadWord.getValue();
    return this.listBadWord;
  },

  /**
   * @param {string} text
   * @returns {boolean}
   */
  isBlockBadWord(text) {
    return this.listBadWord.some((item) => item && text.includes(item));
  },
};

/**
 * @param {BridgeListenerRequestPayload} payload
 * @returns {object}
 */
export const onSendChatMessage = (payload) => {
  if (!(payload?.method === 'POST')) {
    return payload;
  }

  const body = parseBody(payload.requestBody);
  const text = lodash.get(body, 'content.text', '');

  if (!text || !shopeeBadWord.isBlockBadWord(text)) {
    return payload;
  }

  return { cancel: true };
};
