/**
 * Issue apeman id if not exists.
 * @function serverside.middleware.defineApemanIdMiddleware
 * @param {object} context - Server context object.
 * @param {string} context.APEMAN_ID_COOKIE_KEY - Cookie key of apeman id.
 * @returns {function} - A apeman id middleware.
 * @author Taka Okunishi
 *
 */
var uuid = require('../../lib/uuid');
module.exports = function (context) {
    context.assertKeys(['APEMAN_ID_COOKIE_KEY']);

    var domain = context.APEMAN_COOKIE_DOMAIN;
    var Cookies = require("cookies");
    return function (req, res, next) {
        if (!req.apemanId) {
            next(new Error('apemanIdMiddleware requires apemanId method.'));
        }
        var value = req.apemanId();
        if (!value) {
            var cookies = new Cookies(req, res),
                cookieKey = context.APEMAN_ID_COOKIE_KEY;
            value = uuid.uuid();
            cookies.set(cookieKey, value, {
                domain: domain
            });
        }
        next();
    }
};