package link.at17.mid.tushare.data.validator;

import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import link.at17.mid.tushare.data.models.UpdateMethodInfo;
import link.at17.mid.tushare.data.models.UpdateMethodInfo.UpdateParamInfo;
import link.at17.mid.tushare.service.UpdateMethodService;

@Component
public class UpdateMethodInfoValidator implements IValidator, ConstraintValidator<ValidUpdateMethodInfo, UpdateMethodInfo> {

    @Autowired
    private UpdateMethodService updateMethodService; // 内存维护的合法方法表

    @Override
    public boolean isValid(UpdateMethodInfo methodInfo, ConstraintValidatorContext context) {
        if (methodInfo == null) return true;
        
        // 1. 校验 id 是否存在
        if (methodInfo.getId() == null) {
            return invalid(context, "方法 id 为空");
        }
        
        // 2. 校验 id 在内存中是否存储
        UpdateMethodInfo validMethod = updateMethodService.findById(methodInfo.getId());
        if (validMethod == null) {
            return invalid(context, "方法 id 不存在: " + methodInfo.getId());
        }
        
        String name = validMethod.getName();
        
        // 3. 校验参数数量与名称
        List<UpdateParamInfo> incoming = methodInfo.getParams();
        List<UpdateParamInfo> reference = validMethod.getParams();

        if (incoming == null || incoming.size() != reference.size()) {
            return invalid(context, name + " 参数数量不一致: " + methodInfo.getId());
        }
        
        for (int i = 0; i < incoming.size(); i++) {
            UpdateParamInfo in = incoming.get(i);
            UpdateParamInfo ref = reference.get(i);

            if (!Objects.equals(in.getName(), ref.getName())) {
                return invalid(context, name + " 参数名不匹配: " + in.getName());
            }

            if (ref.getAllowedEnumValues() != null &&
                in.getValue() != null &&
                !ref.getAllowedEnumValues().contains(String.valueOf(in.getValue()))) {
                return invalid(context, name + " 参数值非法: " + in.getName() + " : " + in.getValue());
            }
        }

        return true;
    }
}
