text: /* eslint max-lines: ['warn', { max: 99, skipBlankLines: true }] */
  import firebase from 'firebase-admin'
  import { Observable, from } from 'rxjs'
  import { prettify } from '@rampant/logger'
  import { tap, map, mergeMap } from 'rxjs/operators'
  import basicActions from '@rampant-firebase/basic-actions'
  
  // eslint-disable-next-line import/no-unresolved
  import serviceAccount from './firebase-key.json'
  
  const onSnapshot = ref =>
      Observable.create(observer => {
          ref.onSnapshot(snapshot => observer.next(snapshot))
      })
  
  export default ({ id, logger: baseLogger }) => {
      firebase.initializeApp({
          credential: firebase.credential.cert(serviceAccount),
          databaseURL: `https://${id}.firebaseio.com`,
      })
      baseLogger.platform('Firebase Initialized')
      const db = firebase.firestore()
      const logger = baseLogger.child({ plugin: 'firebase' })
  
      return {
          onCollectionChange: collectionId => {
              logger.detail(`Watching [${collectionId}] collection`)
              return onSnapshot(db.collection(collectionId)).pipe(
                  tap(snapshot => {
                      logger.detail(
                          `${
                              snapshot.docChanges().length
                          } changes found in [${collectionId}]:`
                      )
  
                      const readableChanges = snapshot
                          .docChanges()
                          .map(({ doc, type }) => ({
                              id: doc.id,
                              type,
                              new: doc.data(),
                          }))
                      logger.debug(prettify(readableChanges))
                  }),
                  mergeMap(snapshot => from(snapshot.docChanges()))
              )
          },
          onDocumentChange: documentId => {
              logger.detail(`Watching [${documentId}] document`)
              return onSnapshot(db.doc(documentId)).pipe(
                  tap(() => logger.detail(`[${documentId}] has changed:`)),
                  map(snapshot => snapshot.data()),
                  tap(data => logger.debug(prettify(data)))
              )
          },
          ...basicActions({ db, logger }),
          raw: db,
      }
  }
  