"use strict";

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

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

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

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

const activateCharge = async (req, res) => (0, _utils.handler)(_utils.hasShopCharges, async data => {
  const {
    charge_id: chargeId,
    shop,
    token
  } = data.query;
  const admin = await (0, _firebase.getFirebase)();
  const ref = await (0, _firebase.getFirebaseRef)(admin, shop);
  const uid = await ref.get().then(doc => doc.data().uid);
  const shopify = await (0, _shopify.getShopifyApi)(shop, token);
  const redirects = {
    accepted: (0, _shopify.getShopifyRedirectAccepted)(shop, token, uid),
    declined: (0, _shopify.getShopifyRedirectDeclined)(shop)
  };

  try {
    const charge = await (0, _shopify.getShopifyRecurringCharge)(shopify, chargeId);
    const chargeAccepted = charge.status === "accepted";
    await (0, _firebase.setFirebaseSubscriptionStatus)(ref, chargeAccepted);
    await (0, _shopify.activateShopifyRecurringCharge)(shopify, chargeId);
    console.log(`Charges ${charge.status} on ${shop}`);
    res.status(200).redirect(chargeAccepted ? redirects.accepted : redirects.declined);
  } catch (error) {
    console.warn(error);
    res.status(200).redirect(redirects.declined);
  }
})(req, res);

exports.activateCharge = activateCharge;
//# sourceMappingURL=activate-charge.js.map