const fs = require('fs');
const crypto = require('crypto');
const archiver = require('archiver');

function createZip(location) {
  const timestamp = new Date().getTime();
  const key = `${timestamp}|${location}`;
  const hash = crypto.createHash('md5').update(key).digest('hex');
  const destination = `.tmp/app-${hash}.zip`;

  return new Promise((resolve, reject) => {
    if (!fs.existsSync('.tmp')) {
      fs.mkdirSync('.tmp');
    } else if (fs.existsSync(destination)) {
      // Delete existing file (if found)
      fs.unlinkSync(destination);
    }

    const output = fs.createWriteStream(destination);
    const zipArchive = archiver('zip');

    output.on('close', () => {
      resolve(destination);
    });

    zipArchive.on('error', (err) => {
      reject(err);
    });

    zipArchive.pipe(output);
    zipArchive.directory(location, false);
    zipArchive.finalize();
  });
}

module.exports = createZip;
