package containers

import (
	"context"
	"fmt"

	"github.com/google/go-containerregistry/pkg/name"
	"github.com/google/go-containerregistry/pkg/v1/remote"

	"github.com/stacklok/frizbee/pkg/constants"
)

// GetDigest returns the digest of a container image reference.
func GetDigest(ctx context.Context, refstr string) (string, error) {
	ref, err := name.ParseReference(refstr)
	if err != nil {
		return "", fmt.Errorf("failed to parse reference: %w", err)
	}

	return GetDigestFromRef(ctx, ref)
}

// GetDigestFromRef returns the digest of a container image reference
// from a name.Reference.
func GetDigestFromRef(ctx context.Context, ref name.Reference) (string, error) {
	desc, err := remote.Get(ref,
		remote.WithContext(ctx),
		remote.WithUserAgent(constants.UserAgent))
	if err != nil {
		return "", fmt.Errorf("failed to get remote reference: %w", err)
	}

	return desc.Digest.String(), nil
}
