const { createLambda } = require('@now/wrapper/lambda.js');
const crypto = require('crypto');
const { mv, scanDir } = require('@now/wrapper/utils.js');
const path = require('path');

function hashOfStream (hashName, stream) {
  return new Promise((resolve, reject) => {
    const hash = crypto.createHash(hashName);
    stream.on('error', (error) => reject(error));
    stream.on('data', (chunk) => hash.update(chunk));
    stream.on('end', () => resolve(hash.digest('hex')));
  });
}

exports.analyze = async (files, entrypoint) => {
  const entrypointStream = await files[entrypoint].toStream();
  return hashOfStream('sha256', entrypointStream);
};

exports.build = async (files, entrypoint) => {
  // move all user code to 'user' subdirectory
  const userFiles = mv(files, (name) => path.join('user', name));
  const launcherFiles = await scanDir(path.join(__dirname, 'dist'));
  const zipFiles = { ...userFiles, ...launcherFiles };

  return createLambda(zipFiles, 'launcher', 'go1.x', {
    NOW_PHP_SCRIPT: path.join('user', entrypoint)
  });
};
