import { ShopeeShopIdentify } from '@background/store/shop';
import { parseRequest } from '@background/bridge/listener/utils';
import { storageSaveHistoryPrint, storageShopeeShopId, storageShopeeShopName } from '@/plugins/storage/items';
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(),
    storageSaveHistoryPrint.getValue(),
  ]);

  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 storageShopeeShopId.getValue()) || '';
  const shopName = ShopeeShopIdentify.shopName || (await storageShopeeShopName.getValue()) || '';

  pushShopeePrintLogJob(printId, shopId, shopName);

  return {
    printId,
  };
};
