package vulnerability

import (
	grypeDB "github.com/anchore/grype/grype/db/v5"
)

type Metadata struct {
	ID          string
	DataSource  string
	Namespace   string
	Severity    string
	URLs        []string
	Description string
	Cvss        []Cvss
}

type Cvss struct {
	Version        string
	Vector         string
	Metrics        CvssMetrics
	VendorMetadata interface{}
}

type CvssMetrics struct {
	BaseScore           float64
	ExploitabilityScore *float64
	ImpactScore         *float64
}

func NewMetadata(m *grypeDB.VulnerabilityMetadata) (*Metadata, error) {
	if m == nil {
		return nil, nil
	}
	return &Metadata{
		ID:          m.ID,
		DataSource:  m.DataSource,
		Namespace:   m.Namespace,
		Severity:    m.Severity,
		URLs:        m.URLs,
		Description: m.Description,
		Cvss:        NewCvss(m.Cvss),
	}, nil
}

func NewCvss(m []grypeDB.Cvss) []Cvss {
	//nolint:prealloc
	var cvss []Cvss
	for _, score := range m {
		cvss = append(cvss, Cvss{
			Version: score.Version,
			Vector:  score.Vector,
			Metrics: CvssMetrics{
				BaseScore:           score.Metrics.BaseScore,
				ExploitabilityScore: score.Metrics.ExploitabilityScore,
				ImpactScore:         score.Metrics.ImpactScore,
			},
			VendorMetadata: score.VendorMetadata,
		})
	}
	return cvss
}

func NewCvssMetrics(baseScore, exploitabilityScore, impactScore float64) CvssMetrics {
	return CvssMetrics{
		BaseScore:           baseScore,
		ExploitabilityScore: &exploitabilityScore,
		ImpactScore:         &impactScore,
	}
}
