const _ = require('lodash');

const CACHE_ID = 'last_viewed_organization';
const CACHE_OPTIONS = { maxAge: 300000 };

const CACHE_FIELDS = [ 'id', 'name', 'organization_type', 'subscription_plan' ];

module.exports = {
    getDetails, storeDetails
};

function getDetails(req, orgId) {
    let cache;

    try { cache = JSON.parse(req.cookies[CACHE_ID]); }
    catch(e) { return; }

    let complete = cache && String(cache.id) === String(orgId);

    for (let i = 0; i < CACHE_FIELDS.length && complete; i++)
        complete &= cache[CACHE_FIELDS[i]] !== undefined;

    return complete ? cache : null;
}

function storeDetails(res, data) {
    if (!data || !data.id || !res)
        return data;

    let cachedValue = JSON.stringify(_.pick(data, CACHE_FIELDS));
    res.cookie(CACHE_ID, cachedValue, CACHE_OPTIONS);

    return data;
}
