package connector_throttle

import (
	"context"

	"github.com/pingcap-inc/nexuscrm-connectors/features/namedcredential"
)

// CredentialResolver resolves a connector credential reference to its canonical
// identity (stable row ID), owning pack namespace, and active state, without
// fetching or decrypting the secret.
//
// canonicalID is the stable primary key of the NamedCredential definition row.
// Because _System_NamedCredential.DeveloperName uses utf8mb4_unicode_ci
// collation, case-variant credentialRefs (e.g. "MyCred" and "mycred") resolve
// to the same definition row and therefore return the same canonicalID. The
// throttler uses canonicalID as the bucket key so case-variant refs share one
// token bucket and cannot bypass per-credential quota.
type CredentialResolver interface {
	ResolveCredentialPack(ctx context.Context, credentialRef string) (canonicalID, namespace string, active bool, err error)
}

// NewNamedCredentialResolver adapts namedcredential.Service to CredentialResolver.
// It calls Service.ResolveCredentialPack which applies the same OwnerPack→active
// gate as ResolveCredentialValue without decrypting the secret bytes.
func NewNamedCredentialResolver(svc *namedcredential.Service) CredentialResolver {
	return &namedCredentialResolver{svc: svc}
}

type namedCredentialResolver struct{ svc *namedcredential.Service }

func (r *namedCredentialResolver) ResolveCredentialPack(ctx context.Context, ref string) (string, string, bool, error) {
	return r.svc.ResolveCredentialPack(ctx, ref)
}
