/**
 * MQTT Broker 服务器
 * 使用 aedes 并配置协议兼容性
 */

const aedes = require('aedes')({
  // 兼容所有MQTT协议版本
  protocolVersion: 4 // 支持 MQTT 5.0，向下兼容 3.1.1 和 3.1
});

const net = require('net');

// 配置参数
const PORT = 1883;
const HOST = '0.0.0.0';

// 简化认证 - 允许所有连接（测试用）
aedes.authenticate = (client, username, password, callback) => {
  console.log(`[认证请求] 客户端: ${client.id}, 用户名: ${username || '无'}`);
  console.log(`[协议版本] ${client.version}`);

  // 测试阶段：允许所有连接
  callback(null, true);
};

// 客户端连接事件
aedes.on('client', (client) => {
  console.log(`[客户端连接] ${client.id} 已连接`);
  console.log(`[当前连接数] ${aedes.connectedClients}`);
});

// 客户端断开事件
aedes.on('clientDisconnect', (client) => {
  console.log(`[客户端断开] ${client.id} 已断开`);
});

// 消息发布事件
aedes.on('publish', (packet, client) => {
  if (client) {
    const payload = packet.payload.toString();
    console.log(`[消息发布] 主题: ${packet.topic}`);
    console.log(`[发布者] ${client.id}`);
    console.log(`[消息内容] ${payload}`);

    try {
      const data = JSON.parse(payload);
      console.log(`[水质数据] 温度:${data.temp}°C, pH:${data.ph}, COD:${data.cod}`);
    } catch (e) {}
    console.log('---');
  }
});

// 订阅事件
aedes.on('subscribe', (subscriptions, client) => {
  console.log(`[订阅] 客户端 ${client.id} 订阅了:`);
  subscriptions.forEach(sub => {
    console.log(`  - 主题: ${sub.topic}`);
  });
});

// 创建TCP服务器
const server = net.createServer(aedes.handle);

// 启动服务器
server.listen(PORT, HOST, () => {
  console.log('========================================');
  console.log('   MQTT Broker 服务器已启动');
  console.log('========================================');
  console.log(`监听地址: mqtt://${HOST}:${PORT}`);
  console.log(`支持协议: MQTT 3.1 / 3.1.1 / 5.0`);
  console.log('----------------------------------------');
  console.log('MQTTX / HarmonyOS 连接配置:');
  console.log('  - 主机: 192.168.128.190');
  console.log('  - 端口: 1883');
  console.log('  - 用户名: admin (可选)');
  console.log('  - 密码: admin (可选)');
  console.log('  - 发布主题: sea_status');
  console.log('========================================');
});

server.on('error', (err) => {
  console.error('服务器错误:', err);
  process.exit(1);
});

process.on('SIGINT', () => {
  console.log('\n正在关闭...');
  aedes.close(() => {
    server.close();
    process.exit(0);
  });
});