const _ = require('lodash');
const fetch = require('node-fetch');
const querystring = require('querystring');
const log = require('../common/log');
const random = require('../common/random');
const dnsUtil = require('../dns');

function getDomains(req, res) {
    let requestUrl = `${req.context.config.api.directory}/admin/organizations/${req.params.org_id}/domains/`;
    let query = {
        page: req.params.page
    };

    requestUrl += '?' + querystring.stringify(query);

    return log(fetch)(requestUrl, { method: 'get', headers: req.context.headers })
        .then(response => response.json())
        .then(data => {
            if (data.result) {
                let requests = data.result.map(domain => {
                    domain.id = random.getString(8);

                    return Promise.all([
                        getGendarmeDetails(req, domain.name),
                        getDkim(req, domain.name),
                        getOwnershipDetails(req, domain.name),
                        dnsUtil.getRecords(req, domain.name)
                    ])
                    .then(([gendarmeDetails, dkim, ownership, dns]) => {
                        Object.assign(
                            domain,
                            gendarmeDetails || {},
                            { ownership, dns, dkim }
                        );

                        let { gendarme: { dkim: gendarmeDkim } } = gendarmeDetails;

                        if (gendarmeDkim) {
                            let relevantDkimEntry = gendarmeDkim.find(item => item.selector === dkim.selector);

                            if (relevantDkimEntry) {
                                dkim.actual_value = relevantDkimEntry.value;
                            }
                        }

                        return domain;
                    })
                    .catch(() => domain);
                });
                return Promise.all(requests).then(() => data);
            }
            return data;
        })
        .catch(error => ({}));
}

function getDkim(req, domain) {
    const requestUrl = `${req.context.config.api.fouras}/domain/status?domain=${encodeURIComponent(domain)}`;
    const headers = {
        'X-Ya-Service-Ticket': _.get(req.context, 'tvm_tickets.fouras')
    };

    return log(fetch)(requestUrl, { method: 'get', headers })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'ok') {
                return data.response;
            }
        })
        .catch(error => {});
}

function getGendarmeDetails(req, domain) {
    const requestUrl = `${req.context.config.api.gendarme}/domain/status?name=${encodeURIComponent(domain)}`;
    const headers = {
        'X-Ya-Service-Ticket': _.get(req.context, 'tvm_tickets.gendarme')
    };

    return log(fetch)(requestUrl, { method: 'get', headers })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'ok') {
                return {
                    mx: _.get(data, 'response.mx.match'),
                    delegated: _.get(data, 'response.ns.match'),
                    gendarme: data.response
                };
            }
        })
        .catch(error => {});
}

function getOwnershipDetails(req, domain) {
    let requestUrl = `${req.context.config.api.directory}/admin/organizations/${req.params.org_id}/domains/${domain}/`;

    return log(fetch)(requestUrl, { method: 'get', headers: req.context.headers })
        .then(response => response.json())
        .catch(error => ({}));
}

module.exports = getDomains;
