const inquirer = require('inquirer');

function checkForExistingRelease(s3Client, bucket, prefix) {
  return new Promise(function (resolve, reject) {
    var query = s3Client.listObjects({
      s3Params: {
        Bucket: bucket,
        MaxKeys: 2,
        Prefix: prefix
      }
    });
    query.once('error', function (err) {
      console.error('An error occured while checking S3 bucket for existing release.', err);
      reject(); // todo confirm if should break release
    });
    query.on('data', function () {
      if (!query.objectsFound) {
        resolve();
        return;
      }

      query.abort();
      return inquirer.prompt({
        message: 'This version already exists in the bucket. Overwrite?',
        name: 'confirm',
        type: 'confirm',
        default: false
      }).then(function (value) {
        if (value.confirm) { resolve(); }
        else { reject(); }
      });
    });
  });
}

module.exports = checkForExistingRelease;
