const _ = require('lodash');
const fetch = require('node-fetch');
const log = require('../common/log');
const cache = require('../common/cache');

const CACHE_ID = 'last_viewed_organization';
const CACHED_KEYS = [ 'id', 'shard', 'name', 'organization_type', 'subscription_plan', 'is_blocked' ];

const CACHE_ENABLED = true;

function getDetails(req, res, options) {
    let { orgId, allowCache } = options;
    let cachedDetails;

    if (CACHE_ENABLED && allowCache) {
        cachedDetails = cache.read(req, CACHE_ID, { id: Number(orgId) });
    }

    if (cachedDetails)
        return Promise.resolve(cachedDetails);

    let requestUrl = `${req.context.config.api.directory}/admin/organizations/${orgId || req.params.org_id}/`;
    return log(fetch)(requestUrl, { method: 'get', headers: req.context.headers })
        .then(response => response.json())
        .then(data => {
            return Object.assign(
                { id: orgId || req.params.org_id },
                CACHE_ENABLED ? cache.push(req, res, CACHE_ID, data, CACHED_KEYS) : data
            );
        })
        .catch(error => {});
}

module.exports = getDetails;
