var express = require('express'),
    router  = express.Router(),
    Promise = require('bluebird'),
    debug   = require('debug')('sabesp:routes'),
    moment  = require('moment'),
    Mongo   = require('./lib/Mongo'),
    Helper  = require('./lib/Helper'),
    Sabesp  = require('./lib/Sabesp'),
    api     = require('./lib/APIVersions'),
    token;

Sabesp.getToken()
  .then(function(resolve) {
    token = resolve;
  });

router.get('/v1/:date?', function (req, res, next) {
  var date = req.params.date || Helper.today();
  _isCached(date)
    .then(function(resolve) {
      api.v1(resolve, res);
    })
    .catch(next);
});

router.get('/v2/:date?', function (req, res, next) {
  var date = req.params.date || Helper.today();
  _isCached(date)
    .then(function(resolve) {
      api.v2(resolve, res);
    })
    .catch(next);
});

router.get('/:date?', function (req, res, next) {
  if (!(req.params.date === undefined && /\d{4}-\d{2}\d{2}$/.test(req.params.date))) {
    return next();
  }
  var date = req.params.date || Helper.today();
  _isCached(date)
    .then(function(resolve) {
      api.v0(resolve, res);
    })
    .catch(next);
});

router.get('/loaderio-deb75e3581d893735fd6e5050757bdb2', function (req, res, next) {
  res.send('loaderio-deb75e3581d893735fd6e5050757bdb2');
});

function _isCached (date) {
  return new Promise(function(resolve, reject) {
    Mongo.findOne('dams', { date: date }, function(err, result) {
      if (result) {
        resolve(result);
      } else {
        Sabesp.fetch(date, token).then(function(result) {
          if (_isValidDate(result, date)) {
            Mongo.insert('dams', result, function(err, result) {
              if (err) { debug('err', err); }
            });
          }
          resolve(result);
        })
        .catch(function(err) {
          reject(err);
        });
      }
    });
  });
}

function _isValidDate(result, date) {
  return (date !== '') && (moment(date) < moment(Helper.today())) && (result.date !== '');
}

module.exports = router;

@@ -892,14 +892,31 @@
 %7B%0A  
-if (!(
+var isValidDateParam = 
 req.
@@ -927,17 +927,17 @@
 ms.date 
-=
+!
 == undef
@@ -944,16 +944,17 @@
 ined && 
+!
 /%5Cd%7B4%7D-%5C
@@ -986,17 +986,40 @@
 ms.date)
-)
+;%0A  if (isValidDateParam
 ) %7B%0A    

Fix route / with isValidDateParam