package com.usky.common.security.feign;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.usky.common.core.bean.ApiResult;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
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;

import static com.usky.common.security.feign.FeignAutoConfiguration.T_REQUEST_ID;

@RestControllerAdvice(basePackages = "com.usky")
@Slf4j
public class BaseResponseAdvice implements ResponseBodyAdvice<Object> {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object object, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        //Feign请求时通过拦截器设置请求头，如果是Feign请求则直接返回实体对象
        boolean isFeign = serverHttpRequest.getHeaders().containsKey(T_REQUEST_ID);

        if(isFeign){
            return object;
        }

        if(object instanceof String){
            return objectMapper.writeValueAsString(ApiResult.success(object));
        }

        if(object instanceof ApiResult){
            return object;
        }

        return ApiResult.success(object);
    }

}