package com.ruoyi.web.controller.jarvis;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URI;

/**
 * 旧回调 /wps365-callback：平台校验多为「GET、无 code」须直接 200；真实授权带 code/error 时再 302 到 /kdocs-callback。
 */
@Anonymous
@RestController
public class Wps365ToKdocsCallbackRedirectController {

    @Anonymous
    @GetMapping("/wps365-callback")
    public ResponseEntity<?> wps365Get(HttpServletRequest request,
                                       @RequestParam(value = "code", required = false) String code,
                                       @RequestParam(value = "error", required = false) String error) {
        return handleWps365(request, code, error);
    }

    /**
     * 部分校验或代理可能使用 POST。
     */
    @Anonymous
    @PostMapping("/wps365-callback")
    public ResponseEntity<?> wps365Post(HttpServletRequest request,
                                        @RequestParam(value = "code", required = false) String code,
                                        @RequestParam(value = "error", required = false) String error) {
        return handleWps365(request, code, error);
    }

    private ResponseEntity<?> handleWps365(HttpServletRequest request, String code, String error) {
        if (StringUtils.isBlank(code) && StringUtils.isBlank(error)) {
            String jsonBody = readJsonBodyIfPost(request);
            return KdocsCallbackProbeResponses.callbackReadyJson(request, jsonBody);
        }
        String q = request.getQueryString();
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(URI.create(KdocsCallbackUrlBuilder.absoluteKdocsCallback(request, q)));
        return new ResponseEntity<>(null, headers, HttpStatus.FOUND);
    }

    private static String readJsonBodyIfPost(HttpServletRequest request) {
        if (!"POST".equalsIgnoreCase(request.getMethod())) {
            return null;
        }
        String ct = StringUtils.defaultString(request.getContentType()).toLowerCase();
        if (!ct.contains("application/json")) {
            return null;
        }
        try {
            StringBuilder sb = new StringBuilder();
            try (BufferedReader r = request.getReader()) {
                char[] buf = new char[4096];
                int n;
                while ((n = r.read(buf)) != -1) {
                    sb.append(buf, 0, n);
                }
            }
            return sb.toString();
        } catch (IOException e) {
            return null;
        }
    }
}
