const _ = require('lodash');
const querystring = require('querystring');

module.exports = {
    getContextOptions,
    verifyInput,
    verifyOutput,
    preprocessOutput
};

function getContextOptions(req) {
    const host = req.headers['x-forwarded-host'] || req.get('host');
    const ip = req.ip || _.get(req, 'connection.remoteAddress') || '127.0.0.1';

    return {
        userip: ip,
        sessionid: req.cookies['Session_id'],
        sslsessionid: req.cookies['sessionid2'],
        host: host.split(':')[0]
    };
}

function verifyInput(url, options) {
    let query = querystring.parse(url.split('?')[1]);

    if (!query.sessionid)
        return Promise.reject('Session ID is missing, make sure \'Session_id\' cookie is available');

    if (query.get_user_ticket && !_.get(options, 'headers.X-Ya-Service-Ticket'))
        return Promise.reject('\'X-Ya-Service-Ticket\' header is missing');

    return Promise.resolve();
}

function verifyOutput(data) {
    if (!data || data.type === 'error')
        return Promise.reject(data);

    let status = _.get(data, 'status.value');

    if ([ 'VALID', 'NEED_RESET' ].indexOf(status) === -1) {
        data.message = `Status: '${status}'`;
        return Promise.reject(data);
    }

    if (!data.default_uid) {
        data.message = 'Default account ID is missing';
        return Promise.reject(data);
    }

    return Promise.resolve(data);
}

function preprocessOutput(data) {
    if (data && data.default_uid)
        data.default_user = _.find(data.users, { id: data.default_uid });
    return data;
}
