import assert from 'node:assert';
import BoxError from '../boxerror.js';
import net from 'node:net';


async function getIPv4(config) {
    assert.strictEqual(typeof config, 'object');

    if ('ip' in config) return config.ip;

    throw new BoxError(BoxError.NETWORK_ERROR, 'No IPv4 configured');
}

async function getIPv6(config) {
    assert.strictEqual(typeof config, 'object');

    if ('ip' in config) return config.ip;

    throw new BoxError(BoxError.NETWORK_ERROR, 'No IPv6 configured');
}

async function testIPv4Config(config) {
    assert.strictEqual(typeof config, 'object');

    if (typeof config.ip !== 'string') return new BoxError(BoxError.BAD_FIELD, 'ipv4 must be a string');
    if (!net.isIPv4(config.ip)) return new BoxError(BoxError.BAD_FIELD, 'invalid IPv4');

    return null;
}

async function testIPv6Config(config) {
    assert.strictEqual(typeof config, 'object');

    if (typeof config.ip !== 'string') return new BoxError(BoxError.BAD_FIELD, 'ipv6 must be a string');
    if (!net.isIPv6(config.ip)) return new BoxError(BoxError.BAD_FIELD, 'invalid IPv6');

    return null;
}

export default {
    getIPv4,
    getIPv6,
    testIPv4Config,
    testIPv6Config
};
