import firebase from 'firebase/app';
import '@firebase/auth';
import 'firebase/firestore';
import { updateDeck } from '../data/deck.firebase';
export const deckPublish = async ({ deck: deckSource, config }) => {
  // 1. Update deck meta information
  const deck = await updateDeckMeta(deckSource);
  // 2. Trigger the function that effectively publish
  await publishDeck({ deck, config });
  return deck;
};
export const docPublish = async (_params) => {
  throw new Error('Publish operation not supported.');
};
export const publishUrl = async () => 'https://beta.deckdeckgo.io';
const updateDeckMeta = async (deckSource) => {
  const deck = cleanDeckMeta(deckSource);
  const ownerDeck = updateOwner(deck);
  return updateDeck(ownerDeck);
};
/**
 * If deck was created before user was logged in, the owner_id might have not been set in the offline data
 */
const updateOwner = (deckSource) => {
  if (deckSource.data.owner_id !== undefined) {
    return deckSource;
  }
  const deck = Object.assign({}, deckSource);
  const firebaseUser = firebase.auth().currentUser;
  deck.data.owner_id = firebaseUser === null || firebaseUser === void 0 ? void 0 : firebaseUser.uid;
  return deck;
};
const cleanDeckMeta = (deckSource) => {
  const deck = Object.assign({}, deckSource);
  const now = firebase.firestore.Timestamp.now();
  deck.data.meta.updated_at = now;
  if (deck.data.meta.description === null) {
    deck.data.meta.description = firebase.firestore.FieldValue.delete();
  }
  if (deck.data.meta.tags === null || deck.data.meta.tags.length <= 0) {
    deck.data.meta.tags = firebase.firestore.FieldValue.delete();
  }
  if (deck.data.meta.author === null) {
    deck.data.meta.author = firebase.firestore.FieldValue.delete();
  }
  else if (deck.data.meta.author.social === null) {
    deck.data.meta.author.social = firebase.firestore.FieldValue.delete();
  }
  else {
    deck.data.meta.author.social = Object.keys(deck.data.meta.author.social).reduce((acc, key) => {
      acc[key] =
        deck.data.meta.author.social[key] !== null
          ? deck.data.meta.author.social[key]
          : firebase.firestore.FieldValue.delete();
      return acc;
    }, {});
  }
  return deck;
};
const publishDeck = ({ deck, config }) => {
  return new Promise(async (resolve, reject) => {
    var _a;
    try {
      const token = await ((_a = firebase.auth().currentUser) === null || _a === void 0 ? void 0 : _a.getIdToken());
      const rawResponse = await fetch(`${config.functionsUrl}/publish`, {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`
        },
        body: JSON.stringify({
          deckId: deck.id,
          ownerId: deck.data.owner_id,
          publish: true,
          github: deck.data.github ? deck.data.github.publish : false
        })
      });
      if (!rawResponse || !rawResponse.ok) {
        reject('Something went wrong while publishing the deck');
        return;
      }
      resolve();
    }
    catch (err) {
      reject(err);
    }
  });
};
