import { sendMessage } from 'webext-bridge/content-script';
import {
  EVENT_GET_USER_INFO,
  EVENT_OPEN_POPUP,
  EVENT_GET_LOCAL_SETTING,
  EVENT_GET_SCRIPT_URL,
  EVENT_SHOPEE_SAVE_PRODUCT,
  EVENT_SHOPEE_LISTEN_FETCH,
  EVENT_GET_AFFILIATE_PLATFORM,
  EVENT_SHOPEE_GET_AFFILIATE_CHAT,
  EVENT_SHOPEE_GET_PRODUCT,
  EVENT_SHOPEE_GET_HEADER_SHOPEE,
  EVENT_FETCH_API_AUTOSHOPEE,
} from '@/bridge/config/event';
import { allSetting } from '@/plugins/setting/setting';

const listSetting = Object.keys(allSetting);

/**
 *
 * @returns {Promise<BridgeGetUserData>}
 */
export const bridgeGetUserInfo = async () => sendMessage(EVENT_GET_USER_INFO);

/**
 *
 * @param {string} scriptPath
 * @returns {Promise<string>}
 */
export const bridgeGetScriptUrl = async (scriptPath) => sendMessage(EVENT_GET_SCRIPT_URL, { scriptPath });

/**
 *
 * @param {BridgeOpenPopup} payload
 * @returns
 */
export const bridgeOpenPopupUrl = async (payload) => sendMessage(EVENT_OPEN_POPUP, payload);

/**
 *
 * @param {keyof allSetting} keySetting
 * @returns
 */
export const bridgeGetSetting = async (keySetting) => {
  if (!(keySetting && listSetting.includes(keySetting))) {
    throw {
      msg: 'SETTING_KEY_NOT_FOUND',
      key: keySetting,
    };
  }

  return sendMessage(EVENT_GET_LOCAL_SETTING, { key: keySetting });
};

/**
 *
 * @param {ShopPlatform} platform
 * @returns
 */
export const bridgeGetAffiliateUrl = async (platform) => sendMessage(EVENT_GET_AFFILIATE_PLATFORM, { platform });

/**
 *
 * @param {ShopeeProductData} product
 * @returns
 */
export const bridgeShopeeSaveProductId = async (product) => sendMessage(EVENT_SHOPEE_SAVE_PRODUCT, product);

/**
 *
 * @param {BridgeShopeeAffiliateChatMesage}payload
 * @returns {Promise<text>}
 */
export const bridgeShopeeGetAffiliateChatMesage = async (payload) => sendMessage(EVENT_SHOPEE_GET_AFFILIATE_CHAT, payload);

/**
 *
 * @param {BridgeShopeeListenerFetch}payload
 * @returns {Promise<text>}
 */
export const bridgeShopeeListenFetch = async (payload) => sendMessage(EVENT_SHOPEE_LISTEN_FETCH, payload);

/**
 *
 * @param {BridgeShopeeGetProduct}payload
 * @returns {Promise<ShopeeProductData>}
 */
export const bridgeShopeeGetProduct = async (payload) => sendMessage(EVENT_SHOPEE_GET_PRODUCT, payload);

/**
 *
 * @param {'product'|'search'} by
 * @returns {Promise<Array>}
 */
export const bridgeShopeeGetHeaderProduct = async (by) => sendMessage(EVENT_SHOPEE_GET_HEADER_SHOPEE, { by });

/**
 *
 * @param {BridgeFetchApiPayload} payload
 * @returns {Promise<object>}
 */
export const bridgeFetchApiAutoshopee = async (payload) => sendMessage(EVENT_FETCH_API_AUTOSHOPEE, payload);
