package com.usky.sas.controller.web;

import cn.hutool.core.bean.BeanUtil;
import com.usky.common.core.bean.ApiResult;
import com.usky.sas.domain.SasConfig;
import com.usky.sas.mqtt.MqttService;
import com.usky.sas.service.SasConfigService;
import com.usky.sas.service.vo.SasConfigVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Agbox/Metabus 配置接口
 *
 * 对应 API 文档：
 * GET /prod-api/service-sas/agbox/config
 * PUT /prod-api/service-sas/agbox/config
 * POST /prod-api/service-sas/agbox/mqtt/pause  暂停 MQTT 事件订阅
 * POST /prod-api/service-sas/agbox/mqtt/resume 恢复 MQTT 事件订阅
 */
@RestController
@RequestMapping("/agbox")
public class SasAgboxConfigController {

    @Autowired
    private SasConfigService sasConfigService;

    @Autowired
    private MqttService mqttService;

    /**
     * 查询 Agbox/Metabus 配置（含 MQTT 连接状态、监听状态）
     */
    @GetMapping("/config")
    public ApiResult<SasConfigVo> getConfig() {
        SasConfig config = sasConfigService.getConfig();
        SasConfigVo vo = config == null ? new SasConfigVo() : BeanUtil.toBean(config, SasConfigVo.class);
        vo.setIsConnected(mqttService.getConnectionStatus());
        vo.setIsListening(mqttService.getListeningStatus());
        return ApiResult.success(vo);
    }

    /**
     * 编辑 Agbox/Metabus 配置
     */
    @PutMapping("/config")
    public ApiResult<Void> updateConfig(@RequestBody SasConfig config) {
        sasConfigService.updateConfig(config);
        if (this.mqttService.getConnectionStatus()) {
            this.mqttService.disconnect();
        }

        this.mqttService.reconnect();
        return ApiResult.success();
    }

    /**
     * 暂停 MQTT 事件订阅（不再处理新到达的消息，连接保持）
     */
    @PostMapping("/mqtt/pause")
    public ApiResult<Void> pauseMqttSubscription() {
        mqttService.pauseListening();
        return ApiResult.success();
    }

    /**
     * 恢复 MQTT 事件订阅（继续处理消息）
     */
    @PostMapping("/mqtt/resume")
    public ApiResult<Void> resumeMqttSubscription() {
        mqttService.resumeListening();
        return ApiResult.success();
    }
}

