package cd.casic.plugin.utils;

import com.github.zafarkhaja.semver.Version;
import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.server.ServerWebInputException;

/**
 * @Classname VersionUtils
 * @Description 版本
 * @Date 2025/5/9 17:10
 * @Created by mianbin
 */
@UtilityClass
public class VersionUtils {

    public static boolean satisfiesRequires(String version, String requires) {
        String requiresVersion = StringUtils.trim(requires);
        // an exact version x.y.z will implicitly mean the same as >=x.y.z
        if (requiresVersion.matches("^\\d+\\.\\d+\\.\\d+$")) {
            // If exact versions are not allowed in requires, rewrite to >= expression
            requiresVersion = ">=" + requiresVersion;
        }
        return version.equals("0.0.0") || checkVersionConstraint(version, requiresVersion);
    }

    public static boolean checkVersionConstraint(String version, String constraint) {
        try {
            return StringUtils.isBlank(constraint)
                    || "*".equals(constraint)
                    || Version.parse(version).satisfies(constraint);
        } catch (Exception e) {
            throw new ServerWebInputException("Illegal requires version expression.", null, e);
        }
    }
}
