package models

import (
	"github.com/anchore/grype/grype/vulnerability"
)

type Vulnerability struct {
	VulnerabilityMetadata
	Fix        Fix        `json:"fix"`
	Advisories []Advisory `json:"advisories"`
}

type Fix struct {
	Versions []string `json:"versions"`
	State    string   `json:"state"`
}

type Advisory struct {
	ID   string `json:"id"`
	Link string `json:"link"`
}

func NewVulnerability(vuln vulnerability.Vulnerability, metadata *vulnerability.Metadata) Vulnerability {
	if metadata == nil {
		return Vulnerability{
			VulnerabilityMetadata: NewVulnerabilityMetadata(vuln.ID, vuln.Namespace, metadata),
		}
	}

	advisories := make([]Advisory, len(vuln.Advisories))
	for idx, advisory := range vuln.Advisories {
		advisories[idx] = Advisory{
			ID:   advisory.ID,
			Link: advisory.Link,
		}
	}

	fixedInVersions := vuln.Fix.Versions
	if fixedInVersions == nil {
		// always allocate collections
		fixedInVersions = make([]string, 0)
	}

	return Vulnerability{
		VulnerabilityMetadata: NewVulnerabilityMetadata(vuln.ID, vuln.Namespace, metadata),
		Fix: Fix{
			Versions: fixedInVersions,
			State:    string(vuln.Fix.State),
		},
		Advisories: advisories,
	}
}
