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


const DNSIMPLE_API = 'https://api.dnsimple.com/v2';

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

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

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

async function getAccountId(domainConfig) {
    assert.strictEqual(typeof domainConfig, 'object');

    const [error, response] = await safe(superagent.get(`${DNSIMPLE_API}/accounts`)
        .set('Authorization', `Bearer ${domainConfig.accessToken}`)
        .retry(5)
        .timeout(30 * 1000)
        .ok(() => true));
    if (error) throw new BoxError(BoxError.NETWORK_ERROR, error);
    if (response.status === 401) throw new BoxError(BoxError.ACCESS_DENIED, formatError(response));
    if (response.status !== 200) throw new BoxError(BoxError.EXTERNAL_ERROR, formatError(response));

    const accountId = safe.query(response.body, 'data[0].id', null);
    if (!accountId || typeof accountId !== 'number') throw new BoxError(BoxError.EXTERNAL_ERROR, `Could not determine account id: ${JSON.stringify(response.body)}`);
    return String(accountId);
}

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

    const accountId = await getAccountId(domainConfig);
    const [error, response] = await safe(superagent.get(`${DNSIMPLE_API}/${accountId}/zones?name_like=${zoneName}`)
        .set('Authorization', `Bearer ${domainConfig.accessToken}`)
        .retry(5)
        .timeout(30 * 1000)
        .ok(() => true));
    if (error) throw new BoxError(BoxError.NETWORK_ERROR, error);
    if (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 data in response: ${JSON.stringify(response.body)}`);

    const item = response.body.data.filter(entry => entry.name === zoneName);
    if (item.length === 0) throw new BoxError(BoxError.NOT_FOUND, 'Domain not found');
    return { accountId, zoneId: item[0].id };
}

async function getDnsRecords(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(`get: ${name} in zone ${zoneName} of type ${type}`);

    const { accountId, zoneId } = await getZone(domainConfig, zoneName);
    const [error, response] = await safe(superagent.get(`${DNSIMPLE_API}/${accountId}/zones/${zoneId}/records?name=${name}&type=${type}`)
        .set('Authorization', `Bearer ${domainConfig.accessToken}`)
        .retry(5)
        .timeout(30 * 1000)
        .ok(() => true));
    if (error) throw new BoxError(BoxError.NETWORK_ERROR, error);
    if (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 data in response: ${JSON.stringify(response.body)}`);

    return response.body.data;
}

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: ${name} in zone ${zoneName} of type ${type} with values ${JSON.stringify(values)}`);

    const { accountId, zoneId } = await getZone(domainConfig, zoneName);
    const records = await getDnsRecords(domainConfig, zoneName, name, type);

    // used to track available records to update instead of create
    let i = 0;
    const recordIds = [];

    for (let value of values) {
        let priority = 0;

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

        const data = {
            type,
            name,
            content: value,
            priority,
            ttl: 60
        };

        if (i >= records.length) {
            const [error, response] = await safe(superagent.post(`${DNSIMPLE_API}/${accountId}/zones/${zoneId}/records`)
                .set('Authorization', `Bearer ${domainConfig.accessToken}`)
                .send(data)
                .retry(5)
                .timeout(30 * 1000)
                .ok(() => true));
            if (error) throw new BoxError(BoxError.NETWORK_ERROR, error);
            if (response.status === 401) throw new BoxError(BoxError.ACCESS_DENIED, formatError(response));
            if (response.status !== 201) throw new BoxError(BoxError.EXTERNAL_ERROR, formatError(response));
            recordIds.push(safe.query(response.body, 'data.id'));
        } else {
            const [error, response] = await safe(superagent.patch(`${DNSIMPLE_API}/${accountId}/zones/${zoneId}/records/${records[i].id}`)
                .set('Authorization', `Bearer ${domainConfig.accessToken}`)
                .send(data)
                .retry(5)
                .timeout(30 * 1000)
                .ok(() => true));
            ++i;

            if (error) throw new BoxError(BoxError.NETWORK_ERROR, error);
            if (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(safe.query(response.body, 'data.id'));
        }
    }

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

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

    log('upsert: completed with recordIds:%j', recordIds);
}

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 getDnsRecords(domainConfig, zoneName, name, type);
    return records.map(r => r.content);
}

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: ${name} in zone ${zoneName} of type ${type} with values ${JSON.stringify(values)}`);

    const { accountId, zoneId } = await getZone(domainConfig, zoneName);
    const records = await getDnsRecords(domainConfig, zoneName, name, type);
    const ids = records.map(r => r.id);

    for (const id of ids) {
        const [error, response] = await safe(superagent.del(`${DNSIMPLE_API}/${accountId}/zones/${zoneId}/records/${id}`)
            .set('Authorization', `Bearer ${domainConfig.accessToken}`)
            .retry(5)
            .timeout(30 * 1000)
            .ok(() => true));

        if (error) throw new BoxError(BoxError.NETWORK_ERROR, error);
        if (response.status === 401) throw new BoxError(BoxError.ACCESS_DENIED, formatError(response));
        if (response.status === 404) continue;
        if (response.status !== 204) 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.accessToken || typeof domainConfig.accessToken !== 'string') throw new BoxError(BoxError.BAD_FIELD, 'accessToken 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 = {
        accessToken: domainConfig.accessToken,
        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('dnsimple') !== -1; })) { // can be dnsimple.com or dnsimple-edge.org
        log('verifyDomainConfig: %j does not contain dnsimple NS', nameservers);
        if (!domainConfig.customNameservers) throw new BoxError(BoxError.BAD_FIELD, 'Domain nameservers are not set to dnsimple');
    }

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