import assert from 'node:assert';
import BoxError from '../boxerror.js';
import constants from '../constants.js';
import logger from '../logger.js';
import dig from '../dig.js';
import dns from '../dns.js';
import safe from 'safetydance';
import superagent from '@cloudron/superagent';
import waitForDns from './waitfordns.js';

const { log } = logger('dns/netcup');


const API_ENDPOINT = 'https://ccp.netcup.net/run/webservice/servers/endpoint.php?JSON';

function formatError(response) {
    if (response.body) return `Netcup DNS error [${response.body.statuscode}] ${response.body.longmessage}`;
    else return `Netcup DNS error [${response.status}] ${response.text}`;
}

function removePrivateFields(domainObject) {
    delete domainObject.config.apiPassword;
    return domainObject;
}

function injectPrivateFields(newConfig, currentConfig) {
    if (!Object.hasOwn(newConfig, 'apiPassword')) newConfig.apiPassword = currentConfig.apiPassword;
}

// returns a api session id
async function login(domainConfig) {
    assert.strictEqual(typeof domainConfig, 'object');

    const data = {
        action: 'login',
        param:{
            apikey: domainConfig.apiKey,
            apipassword: domainConfig.apiPassword,
            customernumber: domainConfig.customerNumber
        }
    };

    const [error, response] = await safe(superagent.post(API_ENDPOINT).send(data).ok(() => true));
    if (error) throw new BoxError(BoxError.NETWORK_ERROR, error);
    if (response.status !== 200) throw new BoxError(BoxError.EXTERNAL_ERROR, formatError(response));
    if (!response.body.responsedata.apisessionid) throw new BoxError(BoxError.ACCESS_DENIED, 'invalid api password');

    return response.body.responsedata.apisessionid;
}

async function getAllRecords(domainConfig, apiSessionId, zoneName) {
    assert.strictEqual(typeof domainConfig, 'object');
    assert.strictEqual(typeof apiSessionId, 'string');
    assert.strictEqual(typeof zoneName, 'string');

    log(`getAllRecords: getting dns records of ${zoneName}`);

    const data = {
        action: 'infoDnsRecords',
        param:{
            apikey: domainConfig.apiKey,
            apisessionid: apiSessionId,
            customernumber: domainConfig.customerNumber,
            domainname: zoneName,
        }
    };

    const [error, response] = await safe(superagent.post(API_ENDPOINT).send(data).ok(() => true));
    if (error) throw new BoxError(BoxError.NETWORK_ERROR, error);
    if (response.status !== 200) throw new BoxError(BoxError.EXTERNAL_ERROR, formatError(response));

    return response.body.responsedata.dnsrecords || [];
}

async function upsert(domainObject, location, type, values) {
    assert.strictEqual(typeof domainObject, 'object');
    assert.strictEqual(typeof location, 'string');
    assert.strictEqual(typeof type, 'string');
    assert(Array.isArray(values));

    const domainConfig = domainObject.config,
        zoneName = domainObject.zoneName,
        name = dns.getName(domainObject, location, type) || '@';

    log('upsert: %s for zone %s of type %s with values %j', name, zoneName, type, values);

    const apiSessionId = await login(domainConfig);

    const result = await getAllRecords(domainConfig, apiSessionId, zoneName);

    const records = [];

    values.forEach(function (value) {
        // remove possible quotation
        if (value.charAt(0) === '"') value = value.slice(1);
        if (value.charAt(value.length -1) === '"') value = value.slice(0, -1);

        let priority = null;
        if (type === 'MX') {
            priority = parseInt(value.split(' ')[0], 10);
            value = value.split(' ')[1];
        }

        let record = result.find(function (r) { return r.hostname === name && r.type === type; });
        if (!record) record = { hostname: name, type: type, destination: value, deleterecord: false };
        else record.destination = value;

        if (priority !== null) record.priority = priority;

        records.push(record);
    });

    const data = {
        action: 'updateDnsRecords',
        param:{
            apikey: domainConfig.apiKey,
            apisessionid: apiSessionId,
            customernumber: domainConfig.customerNumber,
            domainname: zoneName,
            dnsrecordset: {
                dnsrecords: records
            }
        }
    };

    const [error, response] = await safe(superagent.post(API_ENDPOINT).send(data).ok(() => true));
    if (error) throw new BoxError(BoxError.NETWORK_ERROR, error);
    if (response.status !== 200) throw new BoxError(BoxError.EXTERNAL_ERROR, formatError(response));
    if (response.body.statuscode !== 2000) throw new BoxError(BoxError.EXTERNAL_ERROR, formatError(response));
}

async function get(domainObject, location, type) {
    assert.strictEqual(typeof domainObject, 'object');
    assert.strictEqual(typeof location, 'string');
    assert.strictEqual(typeof type, 'string');

    const domainConfig = domainObject.config,
        zoneName = domainObject.zoneName,
        name = dns.getName(domainObject, location, type) || '@';

    log('get: %s for zone %s of type %s', name, zoneName, type);

    const apiSessionId = await login(domainConfig);

    const result = await getAllRecords(domainConfig, apiSessionId, zoneName);

    // We only return the value string
    return result.filter(function (r) { return r.hostname === name && r.type === type; }).map(function (r) { return r.destination; });
}

async function del(domainObject, location, type, values) {
    assert.strictEqual(typeof domainObject, 'object');
    assert.strictEqual(typeof location, 'string');
    assert.strictEqual(typeof type, 'string');
    assert(Array.isArray(values));

    const domainConfig = domainObject.config,
        zoneName = domainObject.zoneName,
        name = dns.getName(domainObject, location, type) || '@';

    log('del: %s for zone %s of type %s with values %j', name, zoneName, type, values);

    const apiSessionId = await login(domainConfig);

    const result = await getAllRecords(domainConfig, apiSessionId, zoneName);

    const records = [];

    values.forEach(function (value) {
        // remove possible quotation
        if (value.charAt(0) === '"') value = value.slice(1);
        if (value.charAt(value.length -1) === '"') value = value.slice(0, -1);

        const record = result.find(function (r) { return r.hostname === name && r.type === type && r.destination === value; });
        if (!record) return;

        record.deleterecord = true;

        records.push(record);
    });

    if (records.length === 0) return;

    const data = {
        action: 'updateDnsRecords',
        param:{
            apikey: domainConfig.apiKey,
            apisessionid: apiSessionId,
            customernumber: domainConfig.customerNumber,
            domainname: zoneName,
            dnsrecordset: {
                dnsrecords: records
            }
        }
    };

    const [error, response] = await safe(superagent.post(API_ENDPOINT).send(data).ok(() => true));
    if (error) throw new BoxError(BoxError.NETWORK_ERROR, error);
    if (response.status !== 200) throw new BoxError(BoxError.EXTERNAL_ERROR, formatError(response));
    if (response.body.statuscode !== 2000) throw new BoxError(BoxError.EXTERNAL_ERROR, formatError(response));
}

async function wait(domainObject, subdomain, type, value, options) {
    assert.strictEqual(typeof domainObject, 'object');
    assert.strictEqual(typeof subdomain, 'string');
    assert.strictEqual(typeof type, 'string');
    assert.strictEqual(typeof value, 'string');
    assert(options && typeof options === 'object'); // { interval: 5000, times: 50000 }

    const fqdn = dns.fqdn(subdomain, domainObject.domain);

    await waitForDns(fqdn, domainObject.zoneName, type, value, options);
}

async function verifyDomainConfig(domainObject) {
    assert.strictEqual(typeof domainObject, 'object');

    const domainConfig = domainObject.config,
        zoneName = domainObject.zoneName;

    if (!domainConfig.customerNumber || typeof domainConfig.customerNumber !== 'string') throw new BoxError(BoxError.BAD_FIELD, 'customerNumber must be a non-empty string');
    if (!domainConfig.apiKey || typeof domainConfig.apiKey !== 'string') throw new BoxError(BoxError.BAD_FIELD, 'apiKey must be a non-empty string');
    if (!domainConfig.apiPassword || typeof domainConfig.apiPassword !== 'string') throw new BoxError(BoxError.BAD_FIELD, 'apiPassword must be a non-empty string');
    if ('customNameservers' in domainConfig && typeof domainConfig.customNameservers !== 'boolean') throw new BoxError(BoxError.BAD_FIELD, 'customNameservers must be a boolean');

    const ip = '127.0.0.1';

    const credentials = {
        customerNumber: domainConfig.customerNumber,
        apiKey: domainConfig.apiKey,
        apiPassword: domainConfig.apiPassword,
        customNameservers: !!domainConfig.customNameservers
    };

    if (constants.TEST) return credentials; // this shouldn't be here

    const [error, nameservers] = await safe(dig.resolve(zoneName, 'NS', { timeout: 5000 }));
    if (error && error.code === 'ENOTFOUND') throw new BoxError(BoxError.BAD_FIELD, 'Unable to resolve nameservers for this domain');
    if (error || !nameservers) throw new BoxError(BoxError.BAD_FIELD, error ? error.message : 'Unable to get nameservers');

    if (!nameservers.every(function (n) { return n.toLowerCase().indexOf('dns.netcup.net') !== -1; })) {
        log('verifyDomainConfig: %j does not contains Netcup NS', nameservers);
        if (!domainConfig.customNameservers) throw new BoxError(BoxError.BAD_FIELD, 'Domain nameservers are not set to Netcup');
    }

    const location = 'cloudrontestdns';

    await upsert(domainObject, location, 'A', [ ip ]);
    log('verifyDomainConfig: Test A record added');

    await del(domainObject, location, 'A', [ ip ]);
    log('verifyDomainConfig: Test A record removed again');

    return credentials;
}

export default {
    removePrivateFields,
    injectPrivateFields,
    upsert,
    get,
    del,
    wait,
    verifyDomainConfig
};
