package grype

import (
	"fmt"

	v6 "github.com/anchore/grype/grype/db/v6"
	v6dist "github.com/anchore/grype/grype/db/v6/distribution"
	v6inst "github.com/anchore/grype/grype/db/v6/installation"
	"github.com/anchore/grype/grype/vulnerability"
	"github.com/anchore/grype/internal/log"
)

func LoadVulnerabilityDB(distCfg v6dist.Config, installCfg v6inst.Config, update bool) (vulnerability.Provider, *vulnerability.ProviderStatus, error) {
	client, err := v6dist.NewClient(distCfg)
	if err != nil {
		return nil, nil, fmt.Errorf("unable to create distribution client: %w", err)
	}
	c, err := v6inst.NewCurator(installCfg, client)
	if err != nil {
		return nil, nil, fmt.Errorf("unable to create curator: %w", err)
	}

	if update {
		updated, err := c.Update()
		if err != nil {
			if distCfg.RequireUpdateCheck {
				return nil, nil, fmt.Errorf("unable to update db: %w", err)
			}
			log.WithFields("error", err).Warn("error updating db")
		}
		if !updated {
			log.Debug("no db update found")
		}
	} else {
		log.Debug("skipping db update")
	}

	s := c.Status()
	if s.Error != nil {
		return nil, nil, s.Error
	}

	rdr, err := c.Reader()
	if err != nil {
		return nil, nil, fmt.Errorf("unable to create db reader: %w", err)
	}

	return v6.NewVulnerabilityProvider(rdr), &s, nil
}
