const https = require('https');

const agent = new https.Agent({ rejectUnauthorized: false });

const PVE_HOST  = process.env.PROXMOX_HOST  || 'https://192.168.0.184:8006';
const PVE_TOKEN = process.env.PROXMOX_TOKEN || '';
const PVE_NODE  = process.env.PROXMOX_NODE  || 'hve-01';

async function pveGet(path) {
    const fetch = (await import('node-fetch')).default;
    const res = await fetch(`${PVE_HOST}/api2/json${path}`, {
        headers: { Authorization: `PVEAPIToken=${PVE_TOKEN}` },
        agent,
        signal: AbortSignal.timeout(10000),
    });
    if (!res.ok) throw new Error(`PVE ${res.status}: ${path}`);
    const json = await res.json();
    return json.data;
}

async function getNodeStatus() {
    return pveGet(`/nodes/${PVE_NODE}/status`);
}

async function getVMs() {
    return pveGet(`/nodes/${PVE_NODE}/qemu`);
}

async function getLXCs() {
    return pveGet(`/nodes/${PVE_NODE}/lxc`);
}

async function getStorage() {
    return pveGet(`/nodes/${PVE_NODE}/storage`);
}

async function getTasks() {
    return pveGet(`/nodes/${PVE_NODE}/tasks?limit=30`);
}

async function getDisks() {
    try { return await pveGet(`/nodes/${PVE_NODE}/disks/list`); } catch { return []; }
}

async function getNetworkInterfaces() {
    try { return await pveGet(`/nodes/${PVE_NODE}/network`); } catch { return []; }
}

async function getAll() {
    const [node, vms, lxcs, storage, tasks, disks, network] = await Promise.allSettled([
        getNodeStatus(),
        getVMs(),
        getLXCs(),
        getStorage(),
        getTasks(),
        getDisks(),
        getNetworkInterfaces(),
    ]);

    const val = (r) => r.status === 'fulfilled' ? r.value : null;

    return {
        node:    val(node),
        vms:     val(vms)     || [],
        lxcs:    val(lxcs)    || [],
        storage: val(storage) || [],
        tasks:   val(tasks)   || [],
        disks:   val(disks)   || [],
        network: val(network) || [],
        node_name: PVE_NODE,
        fetched_at: new Date().toISOString(),
    };
}

module.exports = { getAll, getNodeStatus, getVMs, getLXCs, getStorage, getTasks };
