import {Middleware} from '../../server/types.js';
import {NodeConnections, Node} from '../connections.js';
import {HttpServerRequest, HttpServerResponse} from '../../server/exchange.js';

function routes(connections: NodeConnections): Middleware<HttpServerRequest, HttpServerResponse> {
    return [
        async (ctx, next: () => Promise<void>) => {
            if (ctx.method === 'POST' && ctx.path === '/api/nodes') {
                const json = await ctx.request.json;
                if (!Array.isArray(json)) {
                    ctx.response.statusCode = 400
                    ctx.response._res.end();
                } else {
                    const nodes = json as Node[];
                    const result = connections.announce(nodes);
                    const body = JSON.stringify(result);
                    ctx.response.headers.set('content-type', 'application/json');
                    ctx.response.statusCode = 200;
                    ctx.response._res
                        .end(body);
                }
            } else {
                await next();
            }
        },
        async ({method, path, response}, next: () => Promise<void>) => {
            if (method === 'DELETE' && path?.startsWith('/api/nodes/')) {
                const nodeId = path?.substring('/api/nodes/'.length);
                connections.remove(nodeId);
                response.statusCode = 200;
                response._res.end();
            } else {
                await next();
            }
        },
    ];
}
export default routes;
