package com.ruoyi.web.controller.jarvis;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 金山文档 ChallengeURLValidator 等校验会解析响应为 JSON；返回 HTML 会报 unmarshal challenge response json invalid。
 * 无 OAuth code 时返回与开放平台风格接近的 JSON，并回显 query / JSON body 中的字段（如 challenge）。
 */
public final class KdocsCallbackProbeResponses {

    private KdocsCallbackProbeResponses() {
    }

    private static final MediaType JSON_UTF8 = MediaType.parseMediaType("application/json;charset=UTF-8");

    private static final MediaType HTML_UTF8 = MediaType.parseMediaType("text/html;charset=UTF-8");

    private static final String HTML_BODY = "<!DOCTYPE html><html lang='zh-CN'><head><meta charset='UTF-8'><meta name='robots' content='noindex'>"
        + "<title>金山文档授权回调</title></head>"
        + "<body style='font-family:sans-serif;text-align:center;padding:40px;color:#333'>"
        + "<h2>金山文档授权回调</h2>"
        + "<p>此地址用于 OAuth 授权完成后的跳转，请勿直接收藏或打开。</p>"
        + "<p>请在系统中点击「连接金山文档」或「授权」后，由金山文档页面自动跳转到此处。</p>"
        + "</body></html>";

    /**
     * 浏览器直接打开回调页时使用（Accept 偏 HTML）。
     */
    public static ResponseEntity<String> callbackReadyHtmlPage() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(HTML_UTF8);
        return new ResponseEntity<>(HTML_BODY, headers, HttpStatus.OK);
    }

    /**
     * 平台 URL 校验：合法 JSON，兼容 WebOffice/开放平台常见 envelope，并回显校验参数。
     *
     * @param jsonBody POST application/json 时的原始 body，可为 null
     */
    public static ResponseEntity<String> callbackReadyJson(HttpServletRequest request, String jsonBody) {
        JSONObject data = new JSONObject();

        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String n = names.nextElement();
            data.put(n, request.getParameter(n));
        }

        mergeJsonPrimitivesIntoData(data, jsonBody);

        JSONObject root = new JSONObject();
        root.put("code", 0);
        root.put("message", "");
        root.put("result", "ok");
        root.put("data", data);

        if (data.containsKey("challenge")) {
            root.put("challenge", data.get("challenge"));
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(JSON_UTF8);
        return new ResponseEntity<>(root.toJSONString(), headers, HttpStatus.OK);
    }

    private static void mergeJsonPrimitivesIntoData(JSONObject data, String jsonBody) {
        if (StringUtils.isBlank(jsonBody)) {
            return;
        }
        try {
            JSONObject in = JSON.parseObject(jsonBody);
            if (in == null) {
                return;
            }
            for (String k : in.keySet()) {
                Object v = in.get(k);
                if (v == null) {
                    continue;
                }
                if (v instanceof JSONObject || v instanceof JSONArray) {
                    continue;
                }
                if (!data.containsKey(k)) {
                    data.put(k, v);
                }
            }
        } catch (Exception ignored) {
            // 非 JSON 则忽略
        }
    }

}
