package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/nexuscrm/shared/pkg/constants"
	apihostdialect "github.com/pingcap-inc/nexuscrm-api-host/dialect"
)

// DialectPermissionGateProvider adapts the backend permission middleware to the
// dialect transport's neutral gate-provider protocol.
type DialectPermissionGateProvider struct{}

func (DialectPermissionGateProvider) RequireAll(perms []apihostdialect.Permission) []gin.HandlerFunc {
	handlers := make([]gin.HandlerFunc, 0, len(perms))
	for _, perm := range perms {
		handlers = append(handlers, RequirePermission(constants.Permission(perm)))
	}
	return handlers
}

func (DialectPermissionGateProvider) RequireAny(perms []apihostdialect.Permission) gin.HandlerFunc {
	keys := make([]constants.Permission, 0, len(perms))
	for _, perm := range perms {
		keys = append(keys, constants.Permission(perm))
	}
	return RequireAnyPermission(keys...)
}

// RateLimitSubjectFromContext returns the accepted rate-limit subject that
// ScopeEnforcer stores after a scoped request passes.
func RateLimitSubjectFromContext(c *gin.Context) string {
	if c == nil {
		return ""
	}
	// Through the one owner, so the dialect limiter and the app limiter cannot disagree about who a
	// request is: a PAT was previously invisible to both.
	return RateLimitSubject(c)
}
