const _get = require('lodash/get');
const _set = require('lodash/set');
const _cloneDeep = require('lodash/cloneDeep');
const maskCookies = require('./maskCookies');

const MaskedFields = [
    'request.headers.Authorization',
    'request.headers.X-Ya-Service-Ticket',
    'request.headers.X-Ya-User-Ticket',
    'response.body.userTicket',
    'response.body.raw.user_ticket',
    'response.body.password',
    'response.body.tickets.blackbox.ticket',
    'response.body.tickets.directory.ticket',
    'response.body.tickets.directory-api.ticket',
    'response.body.tickets.dns.ticket',
    'response.body.tickets.fouras.ticket',
    'response.body.tickets.gendarme.ticket',
    'response.body.tickets.setter.ticket',
    // legacy
    'response.body.auth.X-Ya-Service-Ticket',
    'response.body.auth.X-Ya-User-Ticket',
    'response.body.tvm_tickets.blackbox',
    'response.body.tvm_tickets.directory',
    'response.body.tvm_tickets.directory_api',
    'response.body.tvm_tickets.dns',
    'response.body.tvm_tickets.fouras',
    'response.body.tvm_tickets.gendarme',
    'response.body.tvm_tickets.setter',
];

const Cookies = [
    'request.headers.cookie',
    'request.headers.Cookie',
    'response.headers.Cookie',
];

const StringifiedFields = [
    'request.body',
];

const MASK = '***';

function maskSensitiveFields(fields) {
    let maskedFields = _cloneDeep(fields);
    let parsedFields = [];

    // parse stringified
    for (let key of StringifiedFields) {
        let value = _get(maskedFields, key);

        if (value) {
            try {
                value = JSON.parse(value);
                _set(maskedFields, key, value);
                parsedFields.push(key);
            } catch (e) {
                // ignore
            }
        }
    }

    // mask fields
    for (let key of MaskedFields) {
        if (_get(maskedFields, key)) {
            _set(maskedFields, key, MASK);
        }
    }

    // mask cookies
    for (let key of Cookies) {
        let cookieHeader = _get(maskedFields, key);

        if (cookieHeader) {
            _set(maskedFields, key, maskCookies(cookieHeader));
        }
    }

    // stringify parsed
    for (let key of parsedFields) {
        let value = _get(maskedFields, key);

        if (value) {
            _set(maskedFields, key, JSON.stringify(value));
        }
    }

    return maskedFields;
}

module.exports = maskSensitiveFields;
