"use strict";

const healthCheckConstants     = require('../../shared/constants/HealthCheckConstants');
const UtilHttpStatus      = require('../../shared/utils/UtilHttpStatus');
const ServerAccessManager = require("../database/utils/ServerAccessManager");
const _ = require('lodash/collection');

exports.healthCheck = async (req, res) => {
    const userId = req.user ? req.user.documentId : null;

    const dsObject = config.get("dataServices");
    const stats = {};
    const objArr = [];
    _.forEach(dsObject, function(obj, key) {
      obj.key = key;
      objArr.push(obj);
    });
    const sendStatus = {"status" : healthCheckConstants.FAIL, stats};
    try{
      await Promise.all(objArr.map(async (obj) => {
        try {
          const provider = require("../healthCheck/providers/HealthCheckProvider")(obj.providerName);
          const opt = {connectionName: obj.key};
          stats[obj.key] = await provider.healthCheck(opt);
        } catch (e) {
          stats[obj.key] = healthCheckConstants.FAIL;
          logger.error(`Health Check Error for ${obj.providerName}: `);
          logger.error(e);
        }
      }));
      try {
        const provider = require("../healthCheck/providers/HealthCheckProvider")('elasticsearch');
        stats.elasticsearch = await provider.healthCheck();
      } catch (e) {
        stats.elasticsearch = healthCheckConstants.FAIL;
        logger.error("Health Check Error for ElasticSearch: ");
        logger.error(e);
      }

      try {
        const provider = require("../healthCheck/providers/HealthCheckProvider")("redis");
        stats.redis = await provider.healthCheck();
      } catch (e) {
        stats.redis = healthCheckConstants.FAIL;
        logger.error("Health Check Error for Redis: ");
        logger.error(e);
      }

      sendStatus.status = healthCheckConstants.OK;
      res.status(UtilHttpStatus.OK).send(sendStatus).end();
    } catch (err){
      logger.error(err);
      sendStatus.error = err.message;
      res.status(UtilHttpStatus.INTERNAL_SERVER_ERROR).send(sendStatus).end();
    }

};
