package apiversion

import (
	"regexp"
	"strconv"
	"strings"
)

const DefaultThreshold = "1.0.0"

type Version struct {
	Major int
	Minor int
	Patch int
}

var versionPattern = regexp.MustCompile(`^v?(\d+)\.(\d+)\.(\d+)$`)

func Parse(header string) (Version, bool) {
	normalized := strings.TrimSpace(header)
	if normalized == "" {
		return Version{}, false
	}

	matches := versionPattern.FindStringSubmatch(normalized)
	if len(matches) != 4 {
		return Version{}, false
	}

	major, err := strconv.Atoi(matches[1])
	if err != nil {
		return Version{}, false
	}
	minor, err := strconv.Atoi(matches[2])
	if err != nil {
		return Version{}, false
	}
	patch, err := strconv.Atoi(matches[3])
	if err != nil {
		return Version{}, false
	}

	return Version{Major: major, Minor: minor, Patch: patch}, true
}

func UseLatest(header string, threshold string) bool {
	currentVersion, ok := Parse(header)
	if !ok {
		return false
	}

	thresholdVersion, ok := Parse(strings.TrimSpace(threshold))
	if !ok {
		thresholdVersion, _ = Parse(DefaultThreshold)
	}

	return compare(currentVersion, thresholdVersion) >= 0
}

func compare(left Version, right Version) int {
	if left.Major != right.Major {
		if left.Major > right.Major {
			return 1
		}
		return -1
	}

	if left.Minor != right.Minor {
		if left.Minor > right.Minor {
			return 1
		}
		return -1
	}

	if left.Patch != right.Patch {
		if left.Patch > right.Patch {
			return 1
		}
		return -1
	}

	return 0
}
