import Router from '@koa/router';
import serverManager from '../server';

const adminRouter = new Router({
  prefix: '/admin'
});

// 获取所有活动端口
adminRouter.get('/ports', (ctx) => {
  ctx.body = {
    success: true,
    ports: serverManager().getActivePorts()
  };
});

// 添加新端口
adminRouter.post('/ports', (ctx) => {
  const { port } = (ctx.request.body as any);
  
  if (!port || isNaN(parseInt(port))) {
    ctx.status = 400;
    ctx.body = { success: false, message: '无效的端口号' };
    return;
  }
  
  const success = serverManager().createServer(parseInt(port));
  ctx.body = { success, port };
});

// 移除端口
adminRouter.delete('/ports/:port', (ctx) => {
  const port = parseInt(ctx.params.port);
  
  if (isNaN(port)) {
    ctx.status = 400;
    ctx.body = { success: false, message: '无效的端口号' };
    return;
  }
  
  const success = serverManager().removeServer(port);
  ctx.body = { success, port };
});

export default adminRouter;