package tech.easyflow.common.web.jsonbody;

import com.mybatisflex.core.util.ConvertUtil;
import com.mybatisflex.core.util.StringUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import tech.easyflow.common.util.RequestUtil;
import tech.easyflow.common.web.exceptions.BusinessException;

import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 将带 {@link JsonBody} 注解的方法参数从共享 JSON 请求体中解析出来。
 */
@Component
public class JsonBodyArgumentResolver implements HandlerMethodArgumentResolver, SmartInitializingSingleton {

    private final RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    /**
     * 创建 JSON 请求体参数解析器。
     *
     * @param requestMappingHandlerAdapter Spring MVC 处理器适配器
     */
    public JsonBodyArgumentResolver(RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
        this.requestMappingHandlerAdapter = requestMappingHandlerAdapter;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void afterSingletonsInstantiated() {
        List<HandlerMethodArgumentResolver> argumentResolvers = requestMappingHandlerAdapter.getArgumentResolvers();
        ArrayList<HandlerMethodArgumentResolver> resolvers = new ArrayList<>(Objects.requireNonNull(argumentResolvers));
        resolvers.add(0, this);
        requestMappingHandlerAdapter.setArgumentResolvers(resolvers);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(JsonBody.class);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer
            , NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {

        JsonBody jsonBody = parameter.getParameterAnnotation(JsonBody.class);
        Class<?> paraClass = parameter.getParameterType();

        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        if (request == null) {
            return null;
        }

        Object result = null;
        Type paraType = parameter.getGenericParameterType();
        if (paraType instanceof TypeVariable) {
            Type variableRawType = JsonBodyParser.getTypeVariableRawType(
                    parameter.getContainingClass(), ((TypeVariable<?>) paraType));
            if (variableRawType != null) {
                paraClass = (Class<?>) variableRawType;
                paraType = variableRawType;
            }
        }
        try {
            Object jsonObjectOrArray = RequestUtil.readJsonObjectOrArray(request);
            result = JsonBodyParser.parseJsonBody(jsonObjectOrArray, paraClass, paraType, jsonBody.value());
        } catch (Exception e) {
            if (jsonBody.skipConvertError()) {
                //ignore
            } else {
                throw new BusinessException(400, 400, "请求参数格式不正确", e);
            }
        }

        if (result == null && StringUtil.hasText(jsonBody.defaultValue())) {
            result = ConvertUtil.convert(jsonBody.defaultValue(), paraClass);
        }

        if ((result == null) && jsonBody.required()) {
            String field = StringUtil.hasText(jsonBody.value()) ? jsonBody.value() : "请求体";
            throw new BusinessException(400, 400, field + " 不能为空");
        }

        return result;
    }


}
