"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.removeFirebaseShop = exports.addFirebaseShop = exports.setFirebaseSubscriptionStatus = exports.getFirebaseToken = exports.getFirebaseDoc = exports.getFirebaseRef = exports.getFirebase = void 0;

var admin = _interopRequireWildcard(require("firebase-admin"));

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

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

let firebaseInstance;

const getFirebase = async () => {
  if (!firebaseInstance) {
    firebaseInstance = await admin.initializeApp({
      credential: admin.credential.cert({
        projectId: _config.FIREBASE_PROJECT_ID,
        clientEmail: _config.FIREBASE_CLIENT_EMAIL,
        privateKey: _config.FIREBASE_PRIVATE_KEY.replace(/\\n/g, "\n")
      }),
      databaseURL: `https://${_config.FIREBASE_PROJECT_ID}.firebaseio.com`
    });
  }

  return firebaseInstance;
};

exports.getFirebase = getFirebase;

const getFirebaseRef = async (admin, shop) => await admin.firestore().collection(`shops/${shop}/apps`).doc(_config.SHOPIFY_APP_NAME);

exports.getFirebaseRef = getFirebaseRef;

const getFirebaseDoc = async (admin, ref) => await admin.firestore().runTransaction(t => t.get(ref));

exports.getFirebaseDoc = getFirebaseDoc;

const getFirebaseToken = async (admin, shop, token) => {
  const customToken = await admin.auth().createCustomToken(`${_config.SHOPIFY_APP_NAME}/${shop.replace(".myshopify.com", "")}`, {
    shopifyToken: token
  });
  return customToken ? customToken : new Error("Unable to generate firebase token");
};

exports.getFirebaseToken = getFirebaseToken;

const setFirebaseSubscriptionStatus = async (ref, accepted, planOverride) => ref.set({
  hasActiveSubscription: accepted,
  subscriptionPlan: planOverride ? planOverride : _config.SHOPIFY_APP_PLAN_NAME
}, {
  merge: true
});

exports.setFirebaseSubscriptionStatus = setFirebaseSubscriptionStatus;

const addFirebaseShop = async (ref, doc, shop, token, customToken) => {
  const data = doc.exists ? {
    hasAppInstalled: true,
    uid: customToken,
    token: token
  } : {
    hasAppInstalled: true,
    uid: customToken,
    token,
    shop,
    hasActiveSubscription: false
  };
  ref.set({ ...data
  }, {
    merge: true
  });
  return !doc.exists;
};

exports.addFirebaseShop = addFirebaseShop;

const removeFirebaseShop = async (admin, shop) => {
  const db = await admin.firestore();
  const shopRef = await db.collection(`shops/${shop}/apps`).doc(_config.SHOPIFY_APP_NAME);
  const result = await shopRef.set({
    hasActiveSubscription: false,
    hasAppInstalled: false
  }, {
    merge: true
  });
  console.log(result);
  if (!result) throw new Error("Failed database update");
  return result;
};

exports.removeFirebaseShop = removeFirebaseShop;
//# sourceMappingURL=firebase.js.map