package com.multictrl.modules.business.q20.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.multictrl.common.exception.RenException;
import com.multictrl.common.utils.Result;
import com.multictrl.modules.business.service.DJIBaseService;
import com.multictrl.modules.business.service.MqttPushService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * Q20 MQTT模拟接口（测试/调试用）
 * - /reply  : 模拟设备对 services 指令的回复（注入 CacheUtils）
 * - /aircraft: 模拟飞机主动上报消息（发布到对应 MQTT topic，经过正常 handler 处理）
 */
@RestController
@RequestMapping("business/q20/mock")
@Tag(name = "Q20 MQTT模拟(测试)")
@RequiredArgsConstructor
public class Q20MockController {

    private final DJIBaseService djiBaseService;
    private final MqttPushService mqttPushService;

    // ────────── 指令模拟回复 ──────────

    @GetMapping("/pending/{deviceSn}")
    @Operation(summary = "获取当前待回复命令信息")
    public Result<Object> getPending(@PathVariable String deviceSn) {
        return new Result<>().ok(djiBaseService.getPendingCmd(deviceSn));
    }

    @PostMapping("/reply/{deviceSn}")
    @Operation(summary = "注入模拟MQTT回复(直接写入缓存，body为完整回复JSON)")
    public Result<Object> injectReply(
            @PathVariable String deviceSn,
            @RequestBody JSONObject replyData) {
        djiBaseService.injectMockReply(deviceSn, replyData);
        return new Result<>().ok("模拟回复已注入");
    }

    // ────────── 飞机主动上报模拟 ──────────

    /**
     * 模拟飞机发布 MQTT 消息到指定 topic
     * topicType: status | osd | events | services_reply
     * 消息由前端构造完整 payload，后端直接转发到对应 topic
     */
    @PostMapping("/aircraft/{deviceSn}")
    @Operation(summary = "模拟飞机上报消息(发布到MQTT topic)")
    public Result<Object> aircraftPublish(
            @PathVariable String deviceSn,
            @RequestParam String topicType,
            @RequestBody JSONObject payload) {
        String topic = buildTopic(deviceSn, topicType);
        // 补充缺失的公共字段
        if (!payload.containsKey("tid"))       payload.set("tid", IdUtil.fastUUID());
        if (!payload.containsKey("bid"))       payload.set("bid", IdUtil.fastUUID());
        if (!payload.containsKey("timestamp")) payload.set("timestamp", System.currentTimeMillis());
        if (!payload.containsKey("gateway"))   payload.set("gateway", deviceSn);
        mqttPushService.pushMessageByClient1(topic, payload.toString());
        return new Result<>().ok("已发布 → " + topic);
    }

    private String buildTopic(String deviceSn, String topicType) {
        return switch (topicType) {
            case "status"         -> "sys/device/"    + deviceSn + "/status";
            case "osd"            -> "thing/device/"  + deviceSn + "/osd";
            case "events"         -> "thing/device/"  + deviceSn + "/events";
            case "services_reply" -> "thing/device/"  + deviceSn + "/services_reply";
            default -> throw new RenException("未知 topicType: " + topicType);
        };
    }
}
