package db

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

type mockStore struct {
	data map[string]map[string][]grypeDB.Vulnerability
}

func newMockStore() *mockStore {
	d := mockStore{
		data: make(map[string]map[string][]grypeDB.Vulnerability),
	}
	d.stub()
	return &d
}

func (d *mockStore) stub() {
	d.data["debian:distro:debian:8"] = map[string][]grypeDB.Vulnerability{
		"neutron": {
			{
				PackageName:       "neutron",
				Namespace:         "debian:distro:debian:8",
				VersionConstraint: "< 2014.1.3-6",
				ID:                "CVE-2014-fake-1",
				VersionFormat:     "deb",
			},
			{
				PackageName:       "neutron",
				Namespace:         "debian:distro:debian:8",
				VersionConstraint: "< 2013.0.2-1",
				ID:                "CVE-2013-fake-2",
				VersionFormat:     "deb",
			},
		},
	}
	d.data["nvd:cpe"] = map[string][]grypeDB.Vulnerability{
		"activerecord": {
			{
				PackageName:       "activerecord",
				Namespace:         "nvd:cpe",
				VersionConstraint: "< 3.7.6",
				ID:                "CVE-2014-fake-3",
				VersionFormat:     "unknown",
				CPEs: []string{
					"cpe:2.3:*:activerecord:activerecord:*:*:*:*:*:rails:*:*",
				},
			},
			{
				PackageName:       "activerecord",
				Namespace:         "nvd:cpe",
				VersionConstraint: "< 3.7.4",
				ID:                "CVE-2014-fake-4",
				VersionFormat:     "unknown",
				CPEs: []string{
					"cpe:2.3:*:activerecord:activerecord:*:*:something:*:*:ruby:*:*",
				},
			},
			{
				PackageName:       "activerecord",
				Namespace:         "nvd:cpe",
				VersionConstraint: "= 4.0.1",
				ID:                "CVE-2014-fake-5",
				VersionFormat:     "unknown",
				CPEs: []string{
					"cpe:2.3:*:couldntgetthisrightcouldyou:activerecord:4.0.1:*:*:*:*:*:*:*",
				},
			},
			{
				PackageName:       "activerecord",
				Namespace:         "nvd:cpe",
				VersionConstraint: "< 98SP3",
				ID:                "CVE-2014-fake-6",
				VersionFormat:     "unknown",
				CPEs: []string{
					"cpe:2.3:*:awesome:awesome:*:*:*:*:*:*:*:*",
				},
			},
		},
	}
}

func (d *mockStore) GetVulnerability(namespace, id string) ([]grypeDB.Vulnerability, error) {
	var results []grypeDB.Vulnerability
	for _, vulns := range d.data[namespace] {
		for _, vuln := range vulns {
			if vuln.ID == id {
				results = append(results, vuln)
			}
		}
	}
	return results, nil
}

func (d *mockStore) SearchForVulnerabilities(namespace, name string) ([]grypeDB.Vulnerability, error) {
	return d.data[namespace][name], nil
}

func (d *mockStore) GetAllVulnerabilities() (*[]grypeDB.Vulnerability, error) {
	return nil, nil
}

func (d *mockStore) GetVulnerabilityNamespaces() ([]string, error) {
	keys := make([]string, 0, len(d.data))
	for k := range d.data {
		keys = append(keys, k)
	}

	return keys, nil
}
