package com.changhu.support.handler;

import com.changhu.common.pojo.model.JsonResult;
import com.changhu.support.interceptor.JsonBodyInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * author: luozhun
 * desc: 处理被标记的方法，将其包装为JsonResult
 * createTime: 2023/8/18 11:45
 */
@Slf4j
@RestControllerAdvice
public class JsonBodyHandler implements ResponseBodyAdvice<Object> {

    @Autowired
    private HttpServletRequest request;

    @Override
    public boolean supports(@NotNull MethodParameter methodParameter, @NotNull Class<? extends HttpMessageConverter<?>> aClass) {
        return request.getAttribute(JsonBodyInterceptor.RESPONSE_ATTRIBUTE) != null && (Boolean) request.getAttribute(JsonBodyInterceptor.RESPONSE_ATTRIBUTE);
    }

    @Override
    public Object beforeBodyWrite(Object result, MethodParameter methodParameter, @NotNull MediaType mediaType, @NotNull Class<? extends HttpMessageConverter<?>> aClass, @NotNull ServerHttpRequest serverHttpRequest, @NotNull ServerHttpResponse serverHttpResponse) {
        return switch (methodParameter.getParameterType().getSimpleName()) {
            case "void" -> JsonResult.success();
            case "JsonResult" -> result;
            default -> JsonResult.success(result);
        };
    }
}