package grype

import (
	"github.com/anchore/grype/grype/db/legacy/distribution"
	v5 "github.com/anchore/grype/grype/db/v5"
	"github.com/anchore/grype/internal/log"
)

func LoadVulnerabilityDB(cfg distribution.Config, update bool) (*v5.ProviderStore, *distribution.Status, error) {
	dbCurator, err := distribution.NewCurator(cfg)
	if err != nil {
		return nil, nil, err
	}

	if update {
		log.Debug("looking for vulnerability database updates")
		_, err := dbCurator.Update()
		if err != nil {
			return nil, nil, err
		}
	}

	storeReader, err := dbCurator.GetStore()
	if err != nil {
		return nil, nil, err
	}

	status := dbCurator.Status()

	p, err := v5.NewVulnerabilityProvider(storeReader)
	if err != nil {
		return nil, &status, err
	}

	s := &v5.ProviderStore{
		VulnerabilityProvider:         p,
		VulnerabilityMetadataProvider: v5.NewVulnerabilityMetadataProvider(storeReader),
		ExclusionProvider:             v5.NewMatchExclusionProvider(storeReader),
		Closer:                        storeReader,
	}

	return s, &status, nil
}
