const fetch = require('node-fetch');
const querystring = require('querystring');
const log = require('./common/log');
const preprocessPagedList = require('./preprocessPagedList');

const PROGRESS_STATUSES = [ 'setup', 'migration', 'finalization', 'rollback' ];
const FAILURE_STATUSES = [ 'error' ];
const POTENTIAL_FAILURE_TIME = 600000; // 10 min

function getMigrationList(req, res) {
    let requestUrl = `${req.context.config.api.directory}/admin/pdd-migrations/`;
    let options = {
        page: req.params.page,
        ordering: '-updated_at'
    };

    if (req.params.filter === 'hanging') {
        options.status = PROGRESS_STATUSES.join(',');
        options.seconds_since_update = Math.floor(POTENTIAL_FAILURE_TIME/1000);
    }

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

    return log(fetch)(requestUrl, { method: 'get', headers: req.context.headers })
        .then(response => response.json())
        .then(data => {
            data.result = (data.result || []).map(item => preprocessItem(req, item));
            return preprocessPagedList(req, data);
        })
        .catch(error => {});
}

function preprocessItem(req, data) {
    if (!data || data._preprocessed)
        return data || {};

    let settings = data.settings || {};
    let dt = Date.now() - (new Date(data.updated_at || data.created_at)).getTime();

    data.probably_failed = (
        dt > POTENTIAL_FAILURE_TIME &&
        FAILURE_STATUSES.indexOf(data.status) === -1
    );

    data.org = {
        id: data.org_id,
        name: settings.orgname,
        domains: { master: settings.domain },
        root_label: settings.deproot,
        environment: data.environment,
        admin: {
            id: settings.uid,
            nickname: settings.admin
        }
    };

    data._preprocessed = true;

    // console.log(JSON.stringify(data, null, 3));
    return data;
}

module.exports = getMigrationList;
