"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getShopifyRedirectAccepted = exports.getShopifyRedirectDeclined = exports.getShopifyRedirectApp = exports.formatShopifyHeaders = exports.createShopifyRecurringCharge = exports.activateShopifyRecurringCharge = exports.getShopifyRecurringCharge = exports.addShopifyWebhooks = exports.getShopifyHeaders = exports.getShopifyAuthUrl = exports.getShopifyAccessToken = exports.getShopifyToken = exports.getShopifyApi = void 0;

var _shopifyToken = _interopRequireDefault(require("shopify-token"));

var _shopifyApiNode = _interopRequireDefault(require("shopify-api-node"));

var _config = require("./config");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// import { Shopify } from "./types"
const getShopifyApi = async (shopName, accessToken) => await new _shopifyApiNode.default({
  shopName,
  accessToken,
  apiVersion: _config.SHOPIFY_API_VERSION
});

exports.getShopifyApi = getShopifyApi;

const getShopifyToken = () => new _shopifyToken.default({
  redirectUri: `${_config.SHOPIFY_APP_URL}/callback`,
  sharedSecret: _config.SHOPIFY_API_SECRET,
  apiKey: _config.SHOPIFY_API_KEY,
  scopes: _config.SHOPIFY_API_SCOPES,
  timeout: 10000
});

exports.getShopifyToken = getShopifyToken;

const getShopifyAccessToken = async query => {
  const token = getShopifyToken();

  if (token.verifyHmac(query)) {
    return await token.getAccessToken(query.shop, query.code);
  } else {
    return new Error("Error validating or generating token");
  }
};

exports.getShopifyAccessToken = getShopifyAccessToken;

const getShopifyAuthUrl = shop => {
  let token = getShopifyToken();
  return token.generateAuthUrl(shop, undefined, token.generateNonce());
};

exports.getShopifyAuthUrl = getShopifyAuthUrl;

const getShopifyHeaders = req => {
  const shop = req.get("x-shopify-shop-domain");
  const accessToken = req.get("x-shopify-access-token");
  const apiVersion = req.get("x-shopify-api-version");
  const graphqlEndpoint = `https://${shop}/admin/api/${apiVersion}/graphql.json`;
  return {
    shop,
    accessToken,
    apiVersion,
    graphqlEndpoint
  };
};

exports.getShopifyHeaders = getShopifyHeaders;

const addShopifyWebhooks = async shopify => {
  try {
    const webhookConfig = _config.SHOPIFY_APP_WEBHOOKS;
    const webhookShopify = await shopify.webhook.list();
    let webhookCreated = false;

    for (const topic of Object.keys(webhookConfig)) {
      const webhookTopic = topic.replace("-", "/");
      const webhookExists = webhookShopify ? webhookShopify.filter(webhook => webhook.topic === webhookTopic) : [];

      if (!webhookExists.length) {
        await shopify.webhook.create({
          topic: webhookTopic,
          address: `${_config.SHOPIFY_APP_URL}/${webhookConfig[topic]}`
        });
        webhookCreated = true;
      }
    }

    return webhookCreated;
  } catch (err) {
    console.log(err);
    return new Error("Failed to create webhooks");
  }
}; //TODO: export const removeShopifyWebhooks = async (shopify: ShopifyApi): Promise<any> => {}


exports.addShopifyWebhooks = addShopifyWebhooks;

const getShopifyRecurringCharge = async (shopify, chargeId) => await shopify.recurringApplicationCharge.get(chargeId);

exports.getShopifyRecurringCharge = getShopifyRecurringCharge;

const activateShopifyRecurringCharge = async (shopify, chargeId) => await shopify.recurringApplicationCharge.activate(chargeId, {});

exports.activateShopifyRecurringCharge = activateShopifyRecurringCharge;

const createShopifyRecurringCharge = async (shopify, shop, token, trial, redirect) => {
  if (_config.SHOPIFY_APP_CUSTOM_PRIVATE) return redirect;

  try {
    const charges = await shopify.recurringApplicationCharge.list();
    const activeCharges = charges ? charges.find(charge => charge.status === "active" && charge.name === _config.SHOPIFY_APP_PLAN_NAME) : false;

    if (!activeCharges && _config.SHOPIFY_APP_PLAN_NAME && _config.SHOPIFY_APP_PLAN_PRICE) {
      let data = {
        name: _config.SHOPIFY_APP_PLAN_NAME,
        price: _config.SHOPIFY_APP_PLAN_PRICE,
        return_url: `${_config.SHOPIFY_APP_URL}/activate-charge?shop=${shop}&token=${token}`
      };
      if (trial) data = { ...data,
        trial_days: _config.SHOPIFY_APP_PLAN_TRIAL
      };
      if (_config.SHOPIFY_APP_PLAN_TEST) data = { ...data,
        test: true
      };
      const charge = await shopify.recurringApplicationCharge.create(data);
      return charge.confirmation_url;
    } else {
      return redirect;
    }
  } catch (err) {
    return new Error("Failed to create charges");
  }
};

exports.createShopifyRecurringCharge = createShopifyRecurringCharge;

const formatShopifyHeaders = accessToken => ({
  "X-Shopify-Access-Token": accessToken,
  "Content-Type": "application/json",
  Accept: "application/json"
});

exports.formatShopifyHeaders = formatShopifyHeaders;

const getShopifyRedirectApp = (shop, token, customToken) => `https://${shop}/admin/apps/${_config.SHOPIFY_APP_NAME_URL}?token=${token}&shop=${shop}&uid=${customToken}`;

exports.getShopifyRedirectApp = getShopifyRedirectApp;

const getShopifyRedirectDeclined = shop => `https://${shop}/admin/apps/${_config.SHOPIFY_APP_NAME_URL}/error/declined`;

exports.getShopifyRedirectDeclined = getShopifyRedirectDeclined;

const getShopifyRedirectAccepted = (shop, token, uid) => `https://${shop}/admin/apps/${_config.SHOPIFY_APP_NAME_URL}?token=${token}&shop=${shop}&uid=${uid}`;

exports.getShopifyRedirectAccepted = getShopifyRedirectAccepted;
//# sourceMappingURL=shopify.js.map