package com.ruoyi.web.controller.jarvis;

import com.ruoyi.common.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 反向代理后拼浏览器可访问的绝对 URL（OAuth 302 用）。
 */
public final class KdocsCallbackUrlBuilder {

    private KdocsCallbackUrlBuilder() {
    }

    public static String absoluteKdocsCallback(HttpServletRequest request, String queryString) {
        String scheme = request.getHeader("X-Forwarded-Proto");
        if (StringUtils.isBlank(scheme)) {
            scheme = request.getScheme();
        } else if (scheme.contains(",")) {
            scheme = scheme.substring(0, scheme.indexOf(',')).trim();
        }
        String host = request.getHeader("Host");
        if (StringUtils.isBlank(host)) {
            int port = request.getServerPort();
            host = request.getServerName();
            if (port != 80 && port != 443) {
                host = host + ":" + port;
            }
        }
        StringBuilder sb = new StringBuilder();
        sb.append(scheme).append("://").append(host).append("/kdocs-callback");
        if (StringUtils.isNotBlank(queryString)) {
            sb.append('?').append(queryString);
        }
        return sb.toString();
    }
}
