package com.evobms.project.iot.controller;

import com.evobms.common.constant.BboxApiConstants;
import com.evobms.common.utils.StringUtils;
import com.evobms.project.iot.service.DeviceTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * OTA状态上报接口控制器
 * 路径：POST /iot/ota/status
 * 头部：Authorization: Bearer <jwt>
 * 请求体：{ "version":"1.0.0", "status":"1" }  // status: 0下载失败，1下载成功（含验证）
 * 返回：{ code(200), success("1") }
 */
@RestController
@RequestMapping("/iot/ota")
@Api(tags = "IoT OTA状态上报")
public class IotOtaController {
    private static final Logger log = LoggerFactory.getLogger(IotOtaController.class);

    @Autowired
    private DeviceTokenService deviceTokenService;

    @PostMapping("/status")
    @ApiOperation("上报OTA升级状态")
    public Map<String, Object> reportOtaStatus(@RequestBody Map<String, String> body,
                                               HttpServletRequest request) {
        Map<String, Object> resp = new HashMap<>();
        try {
            // 设备鉴权（非JWT令牌）
            String sn = deviceTokenService.resolveSn(request);
            if (StringUtils.isEmpty(sn)) {
                resp.put("code", BboxApiConstants.CODE_UNAUTHORIZED);
                resp.put("success", "0");
                return resp;
            }
            String prevVersion = safeTrim(body.get("version"));
            String statusStr = safeTrim(body.get("status"));
            MDC.put("sn", sn);
            MDC.put("version", prevVersion);

            // 规范化状态：仅识别 "1" 为成功，其余按失败处理；仍返回成功表示上报接口调用成功
            String normalizedStatus = "0";
            if ("1".equals(statusStr)) {
                normalizedStatus = "1";
            }

            log.info("OTA状态上报: sn={} prevVersion={} status={} (0失败,1成功)",
                    sn, prevVersion, normalizedStatus);

            // 此处可根据需要更新任务或设备状态（留空实现，避免误改）

            resp.put("code", BboxApiConstants.CODE_SUCCESS);
            resp.put("success", "1");
            return resp;
        } catch (Exception e) {
            log.error("OTA状态上报异常: {}", e.getMessage(), e);
            resp.put("code", BboxApiConstants.CODE_UNAUTHORIZED);
            resp.put("success", "0");
            return resp;
        } finally {
            MDC.clear();
        }
    }

    private static String safeTrim(String s) {
        return s == null ? null : s.trim();
    }
}