import moment from 'moment';
import {
  RequestProductPayload, RequestShopeeClient, RequestSearchPayload,
} from '@background/store/index';
import { genUuid } from '@/lib/utils/utils';
import { SHOPEE_HEADER_KEYS } from '@/constant/shopee';
import { parseRequest } from '@background/bridge/listener/utils';

/**
 * @param {BridgeListenerRequestPayload} payload
 * @returns {Promise<boolean>}
 */
export const onFetchProductId = async (payload) => {
  const {
    query, headers, url, isIgnore,
  } = parseRequest(payload);

  if (isIgnore || !(query.item_id && query.shop_id && headers[SHOPEE_HEADER_KEYS.GET])) {
    return false;
  }

  RequestProductPayload.pushData({
    uuid: genUuid(),
    headers: {
      [SHOPEE_HEADER_KEYS.IGNORE]: 'yes',
      ...headers,
    },
    url,
    query,
    time: moment().unix(),
  });

  return true;
};

/**
 * @param {BridgeListenerRequestPayload} payload
 * @returns {Promise<boolean>}
 */
export const onFetchSearchProduct = async (payload) => {
  const {
    query, headers, url, isIgnore,
  } = parseRequest(payload);

  if (isIgnore || !query.by) {
    return false;
  }

  RequestSearchPayload.pushData({
    uuid: genUuid(),
    headers: {
      [SHOPEE_HEADER_KEYS.IGNORE]: 'yes',
      ...headers,
    },
    url,
    query,
    time: moment().unix(),
  });

  return true;
};

/**
 * @param {BridgeListenerRequestPayload} payload
 * @returns {Promise<boolean>}
 */
export const onFetchClientAll = async (payload) => {
  const {
    query, headers, url, isIgnore,
  } = parseRequest(payload);

  if (isIgnore) {
    return false;
  }

  RequestShopeeClient.pushData({
    uuid: genUuid(),
    headers: {
      [SHOPEE_HEADER_KEYS.IGNORE]: 'yes',
      ...headers,
    },
    url,
    query,
    time: moment().unix(),
  });

  return true;
};
