package vulnerability

import (
	"strings"

	bsfv1 "github.com/buildsafedev/bsf-apis/go/buildsafe/v1"
)

// SortVulnerabilities sorts the vulnerabilities based on the severity.
func SortVulnerabilities(allVuln []*bsfv1.Vulnerability) []*bsfv1.Vulnerability {
	criticalVuln := make([]*bsfv1.Vulnerability, 0, len(allVuln))
	highVuln := make([]*bsfv1.Vulnerability, 0, len(allVuln))
	mediumVuln := make([]*bsfv1.Vulnerability, 0, len(allVuln))
	lowVuln := make([]*bsfv1.Vulnerability, 0, len(allVuln))

	for _, v := range allVuln {
		switch strings.ToLower(v.Severity) {
		case "critical":
			criticalVuln = append(criticalVuln, v)
		case "high":
			highVuln = append(highVuln, v)
		case "medium":
			mediumVuln = append(mediumVuln, v)
		case "low":
			lowVuln = append(lowVuln, v)
		}
	}

	sortedValues := make([]*bsfv1.Vulnerability, 0, len(allVuln))

	addVuln := func(v []*bsfv1.Vulnerability) {
		sortedValues = append(sortedValues, v...)
	}

	addVuln(criticalVuln)
	addVuln(highVuln)
	addVuln(mediumVuln)
	addVuln(lowVuln)

	return sortedValues
}

// DeriveAV derives the attack vector from the vector.
func DeriveAV(vector string) string {
	parts := strings.Split(vector, "/")
	for _, part := range parts {
		if strings.HasPrefix(part, "AV:") {
			switch part[3:] {
			case "N":
				return "Network"
			case "A":
				return "Adjacent Network"
			case "L":
				return "Local"
			case "P":
				return "Physical"
			}
		}
	}
	return ""
}
