import { docPublishData } from '@deckdeckgo/editor';
import { initIndexHTML, initUpload, updateMetaData, uploadPublishFileIC } from './publish.utils';
import { setData } from './data.utils';
import { uploadSocialImage } from './publish.social.utils';
export const publishDoc = async ({ doc: docSource }) => {
  const { id, data } = docSource;
  const { meta } = data;
  // 1. Init and fill HTML
  const indexHTML = await initDocIndexHTML({ doc: docSource });
  const { storageUpload, publishData } = await initUpload({ indexHTML, folder: 'd', meta });
  // 2. Update doc published meta
  const docData = updateMetaData({ data, meta: data.meta, name: data.name, storageUpload });
  // 3. Update doc meta information
  const doc = await setData({ key: `/docs/${id}`, id, data: docData });
  // 4. Upload
  await uploadPublishFileIC(storageUpload);
  // 5. Upload
  await uploadSocialImage({ storageUpload, publishData });
  return {
    storageUpload,
    publishData,
    doc
  };
};
const initDocIndexHTML = async ({ doc }) => {
  const publishData = await docPublishData({ doc });
  const { paragraphs } = publishData;
  const updateTemplateContent = ({ attr, template }) => template.replace('<!-- DECKDECKGO_DOC -->', `<deckgo-doc ${attr || ''}><article>${paragraphs.join('')}</article></deckgo-doc>`);
  const { html } = await initIndexHTML({ publishData, updateTemplateContent, sourceFolder: 'd' });
  return {
    html,
    publishData
  };
};
export const emitDocPublished = (doc) => {
  const { id, data } = doc;
  const deployedDoc = {
    id,
    data: Object.assign(Object.assign({}, data), { deploy: {
        api: {
          status: 'successful',
          updated_at: new Date()
        }
      } })
  };
  const $event = new CustomEvent('docPublished', { detail: deployedDoc });
  document.dispatchEvent($event);
};
