package cn.sikey.mcdisk.config;

import cn.hutool.http.HttpStatus;
import cn.sikey.framework.common.exception.ServiceException;
import cn.sikey.mcdisk.controller.app.passthrough.vo.PassThroughProxyReqVO;
import jakarta.annotation.Resource;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @Author: nelson
 * @Date: 2025/5/29
 * @Description: okhttp工具
 */
@Component
public class OkHttpUtil {

    @Resource
    private OkHttpClient okHttpClient;

    private static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");

    /**
     * 发送POST请求（JSON格式）
     *
     * @param url     请求URL
     * @param json    请求体JSON字符串
     * @param headers 请求头Map
     * @return 响应内容字符串
     * @throws IOException 网络异常
     */
    public String postJson(String url, String json, Map<String, String> headers)  {
        // 创建请求体
        RequestBody body = RequestBody.create(json, JSON_MEDIA_TYPE);

        // 构建请求
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .post(body);

        // 添加请求头
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }

        // 发送请求并获取响应
        try (Response response = okHttpClient.newCall(requestBuilder.build()).execute()) {
            if (!response.isSuccessful()) {
                throw new ServiceException(HttpStatus.HTTP_INTERNAL_ERROR, "请求移动云盘失败");
            }
            ResponseBody responseBody = response.body();
            return responseBody != null ? responseBody.string() : "";
        }catch (IOException e) {
            throw new ServiceException(HttpStatus.HTTP_INTERNAL_ERROR, e.getMessage());
        }
    }


    /**
     * 透传代理
     *
     * @param request 透传代理
     * @return
     */
    public String handleProxyRequest(PassThroughProxyReqVO request)  {

        // 构建请求体
        RequestBody requestBody = RequestBody.create(
                request.getBody().toString(),
                MediaType.parse("application/json")
        );

        // 构建请求头
        Headers.Builder headersBuilder = new Headers.Builder();
        request.getHeaders().forEach((key, value) ->
                headersBuilder.add(key, value.toString()));

        // 构建请求
        Request okRequest = new Request.Builder()
                .url(request.getUrl())
                .method(request.getMethod(),
                        "POST".equalsIgnoreCase(request.getMethod()) ? requestBody : null)
                .headers(headersBuilder.build())
                .build();

        // 执行请求
        try (Response response = okHttpClient.newCall(okRequest).execute()) {
            if (!response.isSuccessful()) {
                throw new ServiceException(HttpStatus.HTTP_INTERNAL_ERROR, "请求移动云盘失败");
            }

            ResponseBody responseBody = response.body();
            return responseBody != null ? responseBody.string() : "";
        }catch (IOException e) {
            throw new ServiceException(HttpStatus.HTTP_INTERNAL_ERROR, e.getMessage());
        }
    }


    /**
     * 关闭OkHttpClient（通常在应用退出时调用）
     */
    public void shutdown() {
        if (okHttpClient != null) {
            okHttpClient.dispatcher().executorService().shutdown();
            okHttpClient.connectionPool().evictAll();
        }
    }
}
