package updates

import (
	"fmt"
	"strings"

	"golang.org/x/mod/semver"
)

func NormalizeVersion(version string) (string, error) {
	trimmed := strings.TrimSpace(version)
	if trimmed == "" {
		return "", ErrInvalidVersion
	}
	if !strings.HasPrefix(trimmed, "v") {
		trimmed = "v" + trimmed
	}
	if !semver.IsValid(trimmed) {
		return "", fmt.Errorf("%w: %s", ErrInvalidVersion, version)
	}
	return trimmed, nil
}

func CompareVersions(left string, right string) (int, error) {
	normalizedLeft, err := NormalizeVersion(left)
	if err != nil {
		return 0, err
	}
	normalizedRight, err := NormalizeVersion(right)
	if err != nil {
		return 0, err
	}

	return semver.Compare(normalizedLeft, normalizedRight), nil
}
