import assert from 'node:assert';
import BoxError from '../boxerror.js';
import logger from '../logger.js';
import dig from '../dig.js';
import dns from '../dns.js';
import network from '../network.js';
import safe from 'safetydance';
import waitForDns from './waitfordns.js';

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


function removePrivateFields(domainObject) {
    return domainObject;
}

// eslint-disable-next-line no-unused-vars
function injectPrivateFields(newConfig, currentConfig) {
}

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

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

    return;
}

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

    return []; // returning ip confuses apptask into thinking the entry already exists
}

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

    return;
}

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 zoneName = domainObject.zoneName;

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

    const location = 'cloudrontestdns';
    const fqdn = dns.fqdn(location, domainObject.domain);

    const ipv4 = await network.getIPv4();
    if (ipv4) {
        const [ipv4Error, ipv4Result] = await safe(dig.resolve(fqdn, 'A', { timeout: 5000 }));
        if (ipv4Error && (ipv4Error.code === 'ENOTFOUND' || ipv4Error.code === 'ENODATA')) throw new BoxError(BoxError.BAD_FIELD, `Unable to resolve IPv4 of ${fqdn}. Please check if you have set up *.${domainObject.domain} to point to this server's IP`);
        if (ipv4Error) throw new BoxError(BoxError.BAD_FIELD, `Unable to resolve IPv4 of ${fqdn}: ${ipv4Error.message}`);
        if (!ipv4Result) throw new BoxError(BoxError.BAD_FIELD, `Unable to resolve IPv4 of ${fqdn}`);

        if (ipv4Result.length !== 1 || ipv4 !== ipv4Result[0]) throw new BoxError(BoxError.EXTERNAL_ERROR, `Domain resolves to ${JSON.stringify(ipv4Result)} instead of IPv4 ${ipv4}`);
    }

    const ipv6 = await network.getIPv6(); // both should be RFC 5952 format
    if (ipv6) {
        const [ipv6Error, ipv6Result] = await safe(dig.resolve(fqdn, 'AAAA', { timeout: 5000 }));
        if (ipv6Error && (ipv6Error.code === 'ENOTFOUND' || ipv6Error.code === 'ENODATA')) throw new BoxError(BoxError.BAD_FIELD, `Unable to resolve IPv6 of ${fqdn}`);
        if (ipv6Error) throw new BoxError(BoxError.BAD_FIELD, `Unable to resolve IPv6 of ${fqdn}: ${ipv6Error.message}`);
        if (!ipv6Result) throw new BoxError(BoxError.BAD_FIELD, `Unable to resolve IPv6 of ${fqdn}`);

        if (ipv6Result.length !== 1 || ipv6 !== ipv6Result[0]) throw new BoxError(BoxError.EXTERNAL_ERROR, `Domain resolves to ${JSON.stringify(ipv6Result)} instead of IPv6 ${ipv6}`);
    }

    return {};
}

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