package com.ruoyi.web.controller.jarvis;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.jarvis.domain.dto.WeComInboundRequest;
import com.ruoyi.jarvis.domain.dto.WeComInboundResult;
import com.ruoyi.jarvis.service.IWeComInboundService;
import com.ruoyi.jarvis.service.IWeComInboundTraceService;
import com.ruoyi.jarvis.service.SuperAdminService;
import com.ruoyi.jarvis.wecom.WxSendWeComPushClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * wxSend 企微回调桥接：HTTPS + 共享密钥，无登录态
 */
@RestController
@RequestMapping("/jarvis/wecom")
public class WeComInboundController {

    public static final String HEADER_SECRET = "X-Jarvis-WeCom-Secret";

    @Value("${jarvis.wecom.inbound-secret:}")
    private String inboundSecret;

    @Resource
    private IWeComInboundService weComInboundService;
    @Resource
    private IWeComInboundTraceService weComInboundTraceService;
    @Resource
    private WxSendWeComPushClient wxSendWeComPushClient;
    @Resource
    private SuperAdminService superAdminService;

    @PostMapping("/inbound")
    public AjaxResult inbound(
            @RequestHeader(value = HEADER_SECRET, required = false) String secret,
            @RequestBody WeComInboundRequest body) {
        if (!StringUtils.hasText(inboundSecret) || !inboundSecret.equals(secret)) {
            return AjaxResult.error("拒绝访问");
        }
        WeComInboundRequest req = body != null ? body : new WeComInboundRequest();
        WeComInboundResult result = weComInboundService.handleInbound(req);
        weComInboundTraceService.recordInbound(req, result.toTraceFullText());
        Map<String, Object> data = new HashMap<>(4);
        data.put("reply", result.getPassiveReply());
        data.put("activePushCount", result.getActivePushContents().size());
        String pipeTouser = superAdminService.resolveTouserPipeForActivePush(req.getFromUserName());
        if (!StringUtils.hasText(pipeTouser) && StringUtils.hasText(req.getFromUserName())) {
            pipeTouser = req.getFromUserName().trim();
        }
        String callbackAgentId = StringUtils.hasText(req.getAgentId()) ? req.getAgentId().trim() : null;
        wxSendWeComPushClient.scheduleActivePushes(pipeTouser, callbackAgentId, result.getActivePushContents());
        return AjaxResult.success(data);
    }
}
