import moment from 'moment';
import { PRINT_DAY_CLEANUP, PLATFORM_MODELS, normalizeTimestamp } from './constant';

export default {
  methods: {
    setupSync() {
      PLATFORM_MODELS.forEach(({ model }) => {
        model.syncRemote();
      });
    },
    async cleanupOldData() {
      const cutoffDate = moment().subtract(PRINT_DAY_CLEANUP, 'days').valueOf();

      try {
        await Promise.all(
          PLATFORM_MODELS.map(({ model }) => this.deleteOldDocuments(model, cutoffDate)),
        );
      } catch (error) {
        this.loggerApi.error('PDF_LOG_CLEANUP_ERROR', error);
      }
    },
    async deleteOldDocuments(model, cutoffDate) {
      try {
        const allDocs = await model.findAll();

        const oldDocs = allDocs.filter((doc) => {
          if (!doc._id || doc._id.startsWith('_design/')) {
            return false;
          }
          const ts = normalizeTimestamp(doc.createdAt);

          if (!ts || isNaN(ts)) {
            return false;
          }

          return ts < cutoffDate;
        });

        if (oldDocs.length === 0) {
          return;
        }

        const docsToDelete = oldDocs.map((doc) => ({
          _id: doc._id,
          _rev: doc._rev,
          _deleted: true,
        }));

        await model.bulkDocs(docsToDelete);
      } catch (error) {
        this.loggerApi.error('PDF_LOG_DELETE_OLD_DOCS_ERROR', error);
      }
    },
  },
};
