package cn.axzo.workflow.server.advice;

import cn.axzo.framework.autoconfigure.web.exception.RespErrorCodeMappingProperties;
import cn.axzo.framework.autoconfigure.web.exception.handler.AbstractExceptionApiResultHandler;
import cn.axzo.framework.domain.web.code.BaseCode;
import cn.axzo.framework.domain.web.code.IRespCode;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;

import java.util.List;

/**
 * 参数校验结果处理器,专门处理 @see MethodArgumentNotValidException
 *
 * @author wangli
 * @since 2023/7/31 13:46
 */
@Component
public class MethodArgumentNotValidExceptionResultHandler extends AbstractExceptionApiResultHandler<MethodArgumentNotValidException> {
    public MethodArgumentNotValidExceptionResultHandler(RespErrorCodeMappingProperties properties) {
        super(properties);
    }

    @Override
    protected IRespCode decode(MethodArgumentNotValidException ex, IRespCode fallbackCode) {
        return BaseCode.BAD_REQUEST;
    }

    @Override
    protected String getMessage(IRespCode respCode, MethodArgumentNotValidException ex) {
        List<ObjectError> allErrors = ex.getAllErrors();
        if (CollectionUtils.isEmpty(allErrors)) {
            return "";
        }
        StringBuffer buffer = new StringBuffer();
        allErrors.forEach(i -> {
            buffer.append(i.getDefaultMessage()).append(System.lineSeparator());
        });

        return buffer.toString();
    }

}
