package namedcredential

import (
	"context"
	"strings"
)

type drainOnlyInstalledPackContextKey struct{}

type drainOnlyInstalledPackScope struct {
	namespace string
	installID string
}

// WithDrainOnlyInstalledPack binds the exact non-active installed-pack
// incarnation that is allowed to resolve pack-owned NamedCredentials while
// draining queue work. Callers should use this only for the exact
// namespace/install-id row already selected for drain-only processing.
func WithDrainOnlyInstalledPack(ctx context.Context, namespace, installID string) context.Context {
	namespace = strings.TrimSpace(namespace)
	installID = strings.TrimSpace(installID)
	if ctx == nil || namespace == "" || installID == "" {
		return ctx
	}
	return context.WithValue(ctx, drainOnlyInstalledPackContextKey{}, drainOnlyInstalledPackScope{
		namespace: namespace,
		installID: installID,
	})
}

// DrainOnlyInstalledPackFromContext returns the exact drain-only installed-pack
// scope bound by WithDrainOnlyInstalledPack.
func DrainOnlyInstalledPackFromContext(ctx context.Context) (namespace, installID string, ok bool) {
	if ctx == nil {
		return "", "", false
	}
	scope, ok := ctx.Value(drainOnlyInstalledPackContextKey{}).(drainOnlyInstalledPackScope)
	if !ok {
		return "", "", false
	}
	namespace = strings.TrimSpace(scope.namespace)
	installID = strings.TrimSpace(scope.installID)
	if namespace == "" || installID == "" {
		return "", "", false
	}
	return namespace, installID, true
}
