
var myArgs = process.argv.slice(2);

if ( myArgs.length < 1 ) {
    console.log("Missing args", myArgs);
    process.exit(0);
}

const IS_REAL = myArgs[0] !== 'test';


// ---

const db = require('qmi-cloud-common/mongo');
const sendEmail = require("qmi-cloud-common/send-email");

async function asyncForEach(array, callback) {
    for (let index = 0; index < array.length; index++) {
        await callback(array[index], index, array);
    }
}

const doSendEmailErrorProvision = async function(p) {
    let msg = `Send prrovision ERROR email - ${p.user.displayName} (${p.user.upn}) about provision '${p._scenarioDoc.title}' (${p._id}) provisioned with 'Errors'`;
    console.log(msg);
    if ( IS_REAL ) {
        db.event.add({ user: p.user._id, provision: p._id, type: 'vms.warning-error' });
        await db.notification.add({ provision: p._id.toString(), type: 'warningError', message: msg });    
        await sendEmail.sendProvisionError(p, p._scenarioDoc);
    }       
};

async function init() {    
    let provisions = await db.provision.get({
        "isDestroyed":false, 
        "isDeleted": false, 
        "status": "error"
    });

    await asyncForEach(provisions.results, async function(p)  {
        await doSendEmailErrorProvision(p);
    });
}

function check() {
    init().then(function(){
        db.mongoose.connection.close()
        process.exit(0);
        
    }).catch(function(e){
        db.mongoose.connection.close()
        console.log("Error", e);
        process.exit(0);
    });
}


// --------------------------------
check();