"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.callback = void 0;

var _shopify = require("../helpers/shopify");

var _firebase = require("../helpers/firebase");

var _utils = require("../helpers/utils");

const callback = async (req, res) => (0, _utils.handler)(_utils.hasShopCallback, async data => {
  const {
    shop,
    code
  } = data.query;
  const admin = await (0, _firebase.getFirebase)();
  const ref = await (0, _firebase.getFirebaseRef)(admin, shop);
  const doc = await (0, _firebase.getFirebaseDoc)(admin, ref);

  try {
    const shopifyToken = await (0, _shopify.getShopifyAccessToken)(data.query);
    const accessToken = shopifyToken.access_token;
    console.log(`Generated Shopify token on ${shop}`);
    const customToken = await (0, _firebase.getFirebaseToken)(admin, shop, accessToken);
    console.log(`Generated Firebase token on ${shop}`);
    const trial = await (0, _firebase.addFirebaseShop)(ref, doc, shop, shopifyToken, customToken);
    console.log(`${trial ? "Added" : "Updated"} Firebase database record on ${shop}`);
    const shopify = await (0, _shopify.getShopifyApi)(shop, accessToken);
    const redirect = (0, _shopify.getShopifyRedirectApp)(shop, accessToken, customToken);
    console.log(`Connected to Shopify Admin API on ${shop}`);
    const recurring = await (0, _shopify.createShopifyRecurringCharge)(shopify, shop, accessToken, trial, redirect);
    if (recurring instanceof Error) throw recurring;

    if (recurring === redirect) {
      await (0, _firebase.setFirebaseSubscriptionStatus)(ref, true, "Custom App");
      console.log(`Skipped Shopify charges on ${shop}`);
    } else {
      console.log(`Created Shopify charges on ${shop}`);
    }

    const webhooks = await (0, _shopify.addShopifyWebhooks)(shopify);
    if (webhooks instanceof Error) throw webhooks;
    if (webhooks) console.log(`Created Shopify webhooks on ${shop}`);
    console.log(`Completed new auth on ${shop}`);
    res.status(200).redirect(recurring);
  } catch (err) {
    console.log(err.message);
    res.status(200).json({
      status: "error",
      body: err.message
    });
  }
})(req, res);

exports.callback = callback;
//# sourceMappingURL=callback.js.map