import assert from 'node:assert';
import constants from '../constants.js';
import BoxError from '../boxerror.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/linode');


const LINODE_ENDPOINT = 'https://api.linode.com/v4';

function formatError(response) {
    return `Linode DNS error [${response.status}] ${response.text}`;
}

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

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

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

    // returns 100 at a time
    const [error, response] = await safe(superagent.get(`${LINODE_ENDPOINT}/domains`)
        .set('Authorization', 'Bearer ' + domainConfig.token)
        .timeout(30 * 1000)
        .retry(5)
        .ok(() => true));

    if (error) throw new BoxError(BoxError.NETWORK_ERROR, error);
    if (response.status === 403 || response.status === 401) throw new BoxError(BoxError.ACCESS_DENIED, formatError(response));
    if (response.status !== 200) throw new BoxError(BoxError.EXTERNAL_ERROR, formatError(response));

    if (!Array.isArray(response.body.data)) throw new BoxError(BoxError.EXTERNAL_ERROR, 'Invalid response');

    const zone = response.body.data.find(d => d.domain === zoneName);

    if (!zone || !zone.id) throw new BoxError(BoxError.NOT_FOUND, 'Zone not found');

    log(`getZoneId: zone id of ${zoneName} is ${zone.id}`);

    return zone.id;
}

async function getZoneRecords(domainConfig, zoneName, name, type) {
    assert.strictEqual(typeof domainConfig, 'object');
    assert.strictEqual(typeof zoneName, 'string');
    assert.strictEqual(typeof name, 'string');
    assert.strictEqual(typeof type, 'string');

    log(`getInternal: getting dns records of ${zoneName} with ${name} and type ${type}`);

    const zoneId = await getZoneId(domainConfig, zoneName);

    let page = 0, more;
    let records = [];

    do {
        const url = `${LINODE_ENDPOINT}/domains/${zoneId}/records?page=${++page}`;

        const [error, response] = await safe(superagent.get(url)
            .set('Authorization', 'Bearer ' + domainConfig.token)
            .timeout(30 * 1000)
            .retry(5)
            .ok(() => true));

        if (error) throw new BoxError(BoxError.NETWORK_ERROR, error);
        if (response.status === 404) throw new BoxError(BoxError.NOT_FOUND, formatError(response));
        if (response.status === 403 || response.status === 401) throw new BoxError(BoxError.ACCESS_DENIED, formatError(response));
        if (response.status !== 200) throw new BoxError(BoxError.EXTERNAL_ERROR, formatError(response));

        records = records.concat(response.body.data.filter(function (record) {
            return (record.type === type && record.name === name);
        }));

        more = response.body.page !== response.body.pages;
    } while (more);

    return { zoneId, records };
}

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) || '';

    const { records } = await getZoneRecords(domainConfig, zoneName, name, type);
    const tmp = records.map(function (record) { return record.target; });
    return tmp;
}

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 { zoneId, records } = await getZoneRecords(domainConfig, zoneName, name, type);
    let i = 0; // used to track available records to update instead of create
    const recordIds = [];

    for (const value of values) {
        const data = {
            type: type,
            ttl_sec: 300 // lowest
        };

        if (type === 'MX') {
            data.priority = parseInt(value.split(' ')[0], 10);
            data.target = value.split(' ')[1];
        } else if (type === 'TXT') {
            data.target = value.replace(/^"(.*)"$/, '$1'); // strip any double quotes
        } else {
            data.target = value;
        }

        if (i >= records.length) {
            data.name = name; // only set for new records

            const [error, response] = await safe(superagent.post(`${LINODE_ENDPOINT}/domains/${zoneId}/records`)
                .set('Authorization', 'Bearer ' + domainConfig.token)
                .send(data)
                .timeout(30 * 1000)
                .retry(5)
                .ok(() => true));

            if (error) throw new BoxError(BoxError.NETWORK_ERROR, error);
            if (response.status === 400) throw new BoxError(BoxError.BAD_FIELD, formatError(response));
            if (response.status === 403 || response.status === 401) throw new BoxError(BoxError.ACCESS_DENIED, formatError(response));
            if (response.status !== 200) throw new BoxError(BoxError.EXTERNAL_ERROR, formatError(response));

            recordIds.push(response.body.id);
        } else {
            const [error, response] = await safe(superagent.put(`${LINODE_ENDPOINT}/domains/${zoneId}/records/${records[i].id}`)
                .set('Authorization', 'Bearer ' + domainConfig.token)
                .send(data)
                .timeout(30 * 1000)
                .retry(5)
                .ok(() => true));

            if (error) throw new BoxError(BoxError.NETWORK_ERROR, error);
            if (response.status === 400) throw new BoxError(BoxError.BAD_FIELD, formatError(response));
            if (response.status === 403 || response.status === 401) throw new BoxError(BoxError.ACCESS_DENIED, formatError(response));
            if (response.status !== 200) throw new BoxError(BoxError.EXTERNAL_ERROR, formatError(response));

            ++i;

            recordIds.push(response.body.id);
        }
    }

    for (let j = values.length + 1; j < records.length; j++) {
        const [error] =  await safe(superagent.del(`${LINODE_ENDPOINT}/domains/${zoneId}/records/${records[j].id}`)
            .set('Authorization', 'Bearer ' + domainConfig.token)
            .timeout(30 * 1000)
            .retry(5)
            .ok(() => true));

        if (error) log(`upsert: error removing record ${records[j].id}: ${error.message}`);
    }
}

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) || '';

    const { zoneId, records } = await getZoneRecords(domainConfig, zoneName, name, type);
    if (records.length === 0) return;

    const tmp = records.filter(function (record) { return values.some(function (value) { return value === record.target; }); });
    if (tmp.length === 0) return;

    for (const r of tmp) {
        const [error, response] = await safe(superagent.del(`${LINODE_ENDPOINT}/domains/${zoneId}/records/${r.id}`)
            .set('Authorization', 'Bearer ' + domainConfig.token)
            .timeout(30 * 1000)
            .retry(5)
            .ok(() => true));
        if (error && !error.response) throw new BoxError(BoxError.NETWORK_ERROR, error);
        if (response.status === 404) return;
        if (response.status === 403 || response.status === 401) throw new BoxError(BoxError.ACCESS_DENIED, formatError(response));
        if (response.status !== 200) 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.token || typeof domainConfig.token !== 'string') throw new BoxError(BoxError.BAD_FIELD, 'token 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 = {
        token: domainConfig.token,
        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.map(function (n) { return n.toLowerCase(); }).indexOf('ns1.linode.com') === -1) {
        log('verifyDomainConfig: %j does not contains linode NS', nameservers);
        if (!domainConfig.customNameservers) throw new BoxError(BoxError.BAD_FIELD, 'Domain nameservers are not set to Linode');
    }

    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
};
