import { ShopeeShopIdentify } from '@background/store/shop';
import { parseRequest } from '@background/bridge/listener/utils';
import { shopeeSetting, platformSetting } from '@/plugins/setting';
import { pushShopeePrintLogJob } from '@/service/print/log';
import { getUserInfo } from '@background/service/index';

/**
 * @param {BridgeListenerRequestPayload} payload
 * @returns {Promise<object>}
 */
export const onSellerPrintOrder = async (payload) => {
  const [{ isAuthed }, saveHistoryPrint] = await Promise.all([
    getUserInfo(),
    platformSetting.saveHistoryPrint.getSync(),
  ]);

  if (!isAuthed || !saveHistoryPrint || !saveHistoryPrint.shopee) {
    return null;
  }

  const { query } = parseRequest(payload);

  if (!query.job_id) {
    return null;
  }

  const printId = query.job_id;
  const shopId = ShopeeShopIdentify.shopId || (await shopeeSetting.shopeeShopId.getSync()) || '';
  const shopName = ShopeeShopIdentify.shopName || (await shopeeSetting.shopeeShopName.getSync()) || '';

  pushShopeePrintLogJob(printId, shopId, shopName);

  return {
    printId,
  };
};
