import axios from 'axios';
import fetchAdapter from '@vespaiach/axios-fetch-adapter';
import sha256 from 'sha256';
import { shopeeSetting } from '@/plugins/setting';
import { configShopeeApi } from '@/config/api';
import lodash from 'lodash';

const apiAffiliate = axios.create({
  baseURL: configShopeeApi.affiliate.graphql,
  timeout: 1000,
  adapter: fetchAdapter,
});

apiAffiliate.interceptors.response.use((response) => response.data);

const queryBuilder = async (payload = {}) => {
  const appId = await shopeeSetting.shopeeAffId.getSync();
  const key = await shopeeSetting.shopeeAffToken.getSync();
  const timestamp = Date.parse(new Date()) / 1000;

  const body = {
    query: payload,
    variables: null,
  };

  const signature = sha256([appId, timestamp, JSON.stringify(body), key].join(''));

  return apiAffiliate.post('/', body, {
    headers: {
      authorization: [`SHA256 Credential=${appId}`, `Timestamp=${timestamp}`, `Signature=${signature}`].join(', '),
    },
  });
};

export const getShortLink = async (url = '') => {
  const listSub = await shopeeSetting.shopeeAffSubId.getSync();

  const { data } = await queryBuilder(`
    mutation {
      generateShortLink(input: {originUrl: "${url}", subIds: ${JSON.stringify(listSub)}}) {
        shortLink
      }
    }
  `);

  return lodash.get(data, 'generateShortLink.shortLink', '');
};
