import assert from 'node:assert';
import BoxError from '../boxerror.js';
import logger from '../logger.js';
import os from 'node:os';
import safe from 'safetydance';

const { log } = logger('network/network-interface');


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

    const ifaces = os.networkInterfaces();
    const iface = ifaces[config.ifname]; // array of addresses
    if (!iface) throw new BoxError(BoxError.NETWORK_ERROR, `No interface named ${config.ifname}`);

    const addresses = iface.filter(i => i.family === 'IPv4').map(i => i.address);
    if (addresses.length === 0) throw new BoxError(BoxError.NETWORK_ERROR, `${config.ifname} does not have any IPv4 address`);
    if (addresses.length > 1) log(`${config.ifname} has multiple ipv4 - ${JSON.stringify(addresses)}. choosing the first one.`);

    return addresses[0];
}

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

    const ifaces = os.networkInterfaces();
    const iface = ifaces[config.ifname]; // array of addresses
    if (!iface) throw new BoxError(BoxError.NETWORK_ERROR, `No interface named ${config.ifname}`);

    const addresses = iface.filter(i => i.family === 'IPv6').map(i => i.address);
    if (addresses.length === 0) throw new BoxError(BoxError.NETWORK_ERROR, `${config.ifname} does not have any IPv6 address`);
    if (addresses.length > 1) log(`${config.ifname} has multiple ipv6 - ${JSON.stringify(addresses)}. choosing the first one.`);

    return addresses[0];
}

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

    if (typeof config.ifname !== 'string') return new BoxError(BoxError.BAD_FIELD, 'ifname is not a string');

    const [error] = await safe(getIPv4(config));
    return error || null;
}

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

    if (typeof config.ifname !== 'string') return new BoxError(BoxError.BAD_FIELD, 'ifname is not a string');

    const [error] = await safe(getIPv6(config));
    return error || null;
}

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