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 { DNS as GCDNS } from '@google-cloud/dns';
import safe from 'safetydance';
import waitForDns from './waitfordns.js';
import _ from '../underscore.js';

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


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

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

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

    return {
        projectId: domainConfig.projectId,
        credentials: {
            client_email: domainConfig.credentials.client_email,
            private_key: domainConfig.credentials.private_key
        },
        customNameservers: !!domainConfig.customNameservers
    };
}

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

    const gcdns = new GCDNS(getDnsCredentials(domainConfig));

    const [error, result] = await safe(gcdns.getZones());
    if (error && error.message === 'invalid_grant') throw new BoxError(BoxError.ACCESS_DENIED, 'The key was probably revoked');
    if (error && error.reason === 'No such domain') throw new BoxError(BoxError.NOT_FOUND, error.message);
    if (error && error.code === 403) throw new BoxError(BoxError.ACCESS_DENIED, error.message);
    if (error && error.code === 404) throw new BoxError(BoxError.NOT_FOUND, error.message);
    if (error) throw new BoxError(BoxError.EXTERNAL_ERROR, error);

    const zone = result[0].filter(function (entry) {
        return entry.metadata.dnsName.slice(0, -1) === zoneName;     // the zone name contains a '.' at the end
    })[0];

    if (!zone) throw new BoxError(BoxError.NOT_FOUND, 'no such zone');

    return zone; //zone.metadata ~= {name="", dnsName="", nameServers:[]}
}

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,
        fqdn = dns.fqdn(location, domainObject.domain);

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

    const zone = await getZoneByName(getDnsCredentials(domainConfig), zoneName);

    const [error, result] = await safe(zone.getRecords({ type: type, name: fqdn + '.' }));
    if (error && error.code === 403) throw new BoxError(BoxError.ACCESS_DENIED, error.message);
    if (error) throw new BoxError(BoxError.EXTERNAL_ERROR, error.message);

    const newRecord = zone.record(type, {
        name: fqdn + '.',
        data: values,
        ttl: 1
    });

    const [changeError] = await safe(zone.createChange({ delete: result[0], add: newRecord }));
    if (changeError && changeError.code === 403) throw new BoxError(BoxError.ACCESS_DENIED, changeError.message);
    if (changeError && changeError.code === 412) throw new BoxError(BoxError.BUSY, changeError.message);
    if (changeError) throw new BoxError(BoxError.EXTERNAL_ERROR, changeError.message);
}

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,
        fqdn = dns.fqdn(location, domainObject.domain);

    const zone = await getZoneByName(getDnsCredentials(domainConfig), zoneName);

    const params = {
        name: fqdn + '.',
        type: type
    };

    const [error, result] = await safe(zone.getRecords(params));
    if (error && error.code === 403) throw new BoxError(BoxError.ACCESS_DENIED, error.message);
    if (error) throw new BoxError(BoxError.EXTERNAL_ERROR, error.message);
    if (result[0].length === 0) return [];

    return result[0][0].data;
}

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,
        fqdn = dns.fqdn(location, domainObject.domain);

    const zone = await getZoneByName(getDnsCredentials(domainConfig), zoneName);

    const [error, result] = await safe(zone.getRecords({ type: type, name: fqdn + '.' }));
    if (error && error.code === 403) throw new BoxError(BoxError.ACCESS_DENIED, error.message);
    if (error) throw new BoxError(BoxError.EXTERNAL_ERROR, error.message);

    const [delError] = await safe(zone.deleteRecords(result[0]));
    if (delError && delError.code === 403) throw new BoxError(BoxError.ACCESS_DENIED, delError.message);
    if (delError && delError.code === 412) throw new BoxError(BoxError.BUSY, delError.message);
    if (delError) throw new BoxError(BoxError.EXTERNAL_ERROR, delError.message);
}

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 (typeof domainConfig.projectId !== 'string') throw new BoxError(BoxError.BAD_FIELD, 'projectId must be a string');
    if (!domainConfig.credentials || typeof domainConfig.credentials !== 'object') throw new BoxError(BoxError.BAD_FIELD, 'credentials must be an object');
    if (typeof domainConfig.credentials.client_email !== 'string') throw new BoxError(BoxError.BAD_FIELD, 'credentials.client_email must be a string');
    if (typeof domainConfig.credentials.private_key !== 'string') throw new BoxError(BoxError.BAD_FIELD, 'credentials.private_key must be a string');
    if ('customNameservers' in domainConfig && typeof domainConfig.customNameservers !== 'boolean') throw new BoxError(BoxError.BAD_FIELD, 'customNameservers must be a boolean');

    const credentials = getDnsCredentials(domainConfig);

    const ip = '127.0.0.1';

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

    const zone = await getZoneByName(credentials, zoneName);

    const definedNS = zone.metadata.nameServers.map(function(r) { return r.replace(/\.$/, ''); });
    if (!_.isEqual(definedNS.sort(), nameservers.sort())) {
        log('verifyDomainConfig: %j and %j do not match', nameservers, definedNS);
        if (!domainConfig.customNameservers) throw new BoxError(BoxError.BAD_FIELD, 'Domain nameservers are not set to Google Cloud DNS');
    }

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