package feeds

import (
	"context"
	"errors"
	"fmt"

	"github.com/operator/command-center/internal/secrets"
)

// FeedURLSecretKey returns the canonical secrets-store key under which a
// given feed's URL (with embedded passkey) is stored. Same shape as the
// rest of the repo's secrets keys: `<kind>:<id>:<purpose>`.
func FeedURLSecretKey(id string) string {
	return "feed:" + id + ":url"
}

// SecretsStore is the subset of the age-encrypted secrets package the
// feeds layer needs. Narrow interface for the same reason the tracker
// adapters use one — keeps the package import surface tight.
type SecretsStore interface {
	Get(ctx context.Context, key string) ([]byte, error)
}

// ResolveURL pulls the feed's URL out of the age-encrypted secrets store.
// Returns ErrFeedNotConfigured (typed) if no URL is registered yet so the
// caller can surface a friendly "no feed configured" message instead of a
// generic 500.
func ResolveURL(ctx context.Context, store SecretsStore, id string) (string, error) {
	if store == nil {
		return "", errors.New("feeds: nil secrets store")
	}
	b, err := store.Get(ctx, FeedURLSecretKey(id))
	if err != nil {
		if errors.Is(err, secrets.ErrNotFound) {
			return "", ErrFeedNotConfigured
		}
		return "", fmt.Errorf("feeds: resolve url for %q: %w", id, err)
	}
	return string(b), nil
}

// ErrFeedNotConfigured signals the operator hasn't placed a URL for this
// feed id yet. Maps to HTTP 404 in the API handler.
var ErrFeedNotConfigured = errors.New("feeds: no URL configured for this feed id")
