import queryString from 'query-string';
import crypto from 'crypto-js';
import { getShopeeSellerCookies } from '@/api/shopee/seller/init';
import { getShopeeSellerLogin, getShopeeWebchatLogin } from '@/api/shopee/seller/index';

const payloadAuth = {
  userId: 0,
  ctoken: '',
  authorization: '',
  token: '',
};

/**
 *
 * @param {object} payload
 * @param {number} payload.userId
 * @param {string} payload.ctoken
 * @param {object} payload.body
 * @param {number} payload.timestamp
 * @param {string} payload.authorization
 * @returns
 */
export const renderPayloadSend = ({
  userId, ctoken, body, timestamp, authorization,
}) => {
  const xv = 1;
  const xs = '396c15ad-6d3e-4018-98be-cef58cb45cd0';

  const version = '7.3.4';
  const verCrypt = 'v1.2';
  const source = 'sc';

  const qsBase = {
    _uid: `0-${userId}`,
    _v: version,
  };

  const payloadQuery = {
    fromID: userId,
    plat: version,
    ver: verCrypt,
    reqID: body.request_id,
    toID: body.to_id,
    timestamp,
    type: body.type,
    strinput: body.type === 'text' ? body.content.text : '',
  };

  const queryStr = queryString.stringify(
    {
      key: xs,
      plat: payloadQuery.plat,
      ver: payloadQuery.ver,
      fromID: payloadQuery.fromID,
      reqID: payloadQuery.reqID,
      toID: payloadQuery.toID,
      timestamp: payloadQuery.timestamp,
      type: payloadQuery.type,
      strinput: payloadQuery.strinput,
    },
    {
      sort: false,
      encode: false,
    },
  );

  const query = {
    ...qsBase,
    _api_source: source,
    csrf_token: ctoken,
  };

  const headers = {
    'x-v': xv,
    'x-s': crypto.SHA256(queryStr).toString(),
    ts: timestamp,
    Authorization: `Bearer ${authorization}`,
  };

  return {
    query,
    headers,
  };
};

export const readySendChat = async () => {
  if (!payloadAuth.authorization) {
    const sellerWebchat = await getShopeeWebchatLogin();
    payloadAuth.authorization = sellerWebchat.token;
    payloadAuth.token = sellerWebchat.p_token;

    const sellerLogin = await getShopeeSellerLogin();
    payloadAuth.userId = sellerLogin.id;

    const sellerCookies = await getShopeeSellerCookies();
    payloadAuth.ctoken = sellerCookies.find((item) => item.name === 'CTOKEN').value;
  }

  return payloadAuth;
};
