const { cleanupInterfaces } = require('../../maintenance/cleanup'); const { logError } = require('../../infrastructure/logger'); const { scheduleInterfacesBroadcast } = require('../admin-backend/interfaces-broadcast'); const { buildInterfacesResponse, removeOrphanedInterfaceIp } = require('../interfaces-data'); function readJsonBody(req) { return new Promise((resolve, reject) => { let body = ''; req.on('data', chunk => { body += chunk; }); req.on('end', () => { try { resolve(body ? JSON.parse(body) : {}); } catch (err) { reject(new Error('Invalid JSON body')); } }); req.on('error', reject); }); } async function handleInterfacesRoutes(req, res) { const urlPath = req.urlPath || new URL(req.url, `https://${req.headers.host}`).pathname; const method = req.method; if (method === 'GET' && urlPath === '/api/interfaces') { try { const payload = await buildInterfacesResponse(); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(payload)); } catch (err) { logError('Admin', `Failed to fetch interfaces: ${err.message}`); res.writeHead(500); res.end(JSON.stringify({ error: 'Failed to fetch interfaces' })); } return true; } if (method === 'POST' && urlPath === '/api/interfaces/remove-ip') { try { const { ip } = await readJsonBody(req); const removedIp = await removeOrphanedInterfaceIp(ip); scheduleInterfacesBroadcast(); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ ok: true, ip: removedIp })); } catch (err) { logError('Admin', `Failed to remove orphaned IP: ${err.message}`); res.writeHead(400); res.end(JSON.stringify({ error: err.message })); } return true; } if (method === 'POST' && urlPath === '/api/cleanup-interfaces') { try { await cleanupInterfaces(); scheduleInterfacesBroadcast(); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('OK'); } catch (err) { logError('Admin', `Failed to cleanup interfaces: ${err.message}`); res.writeHead(500); res.end(err.message); } return true; } return false; } module.exports = { handleInterfacesRoutes };