var Promise = require("bluebird");
var util = require('util');
var moment = require('moment');
var pg = require('pg');

module.exports = {
    process: function(req, res) {
        //YOUR CONNECTION NAME HERE
        var pConfig = sails.config.connections.PostgresqlServer;
        var conString = util.format("postgres://%s:%s@localhost:%s/%s", pConfig.user, pConfig.password, pConfig.port, pConfig.database);

        var client = new pg.Client(conString);
        Promise.promisifyAll(client);

        Users.findOne({code:code})
        .then(function (_user) {
            return Accounts.findOne(data).populateAll();
        })
        .then(function (_account) {
            account = _account;
            return client.connectAsync();
        })
        .then(function(){
            return client.queryAsync('BEGIN');
        })
        .then(function() {
            var sql1 = util.format('UPDATE accounts SET balance = balance - %d, "isUnused" = FALSE WHERE id = %d', bonus, account.id);
            var u1 = client.queryAsync(sql1);
            
            //var t1 = Transactions.create({type:'redemption', amount: bonus, account: account.id});
            var sql2 = util.format('INSERT INTO "transactions" ("type", "amount", "account", "createdAt", "updatedAt") values (\'%s\', \'%s\', \'%s\', \'%s\', \'%s\')', 'redemption', bonus, account.id, postgresNow(), postgresNow());
            var t1 = client.queryAsync(sql2);
            
            //var r = Redemptions.create({amount: bonus, paid: amount, account: account.id});
            var sql3 = util.format('INSERT INTO "redemptions" ("amount", "paid", "account", "createdAt", "updatedAt") values (\'%s\', \'%s\', \'%s\', \'%s\', \'%s\') ', bonus, amount, account.id, postgresNow(), postgresNow());
            var r = client.queryAsync(sql3);
            return Promise.all([bonus, u1, t1, r]);
            
        })
        .then(function () {
            return client.queryAsync('COMMIT');
        })
        .then(function() {
            res.send(data)
        })
        .catch(function(err) {
            client.queryAsync('ROLLBACK');
            res.negotiate(err);
        })
        
    }
};

function postgresNow(){
    return moment().format('YYYY-MM-DD HH:mm:ss ZZ');
}