package ownership

import (
	regionalapiv1 "github.com/tidbcloud/cluster-service-ng/api/tidbcloud/dataplane-manager/v1"
	"github.com/tidbcloud/infra-provider/regional-server/api/v1alpha1"
	bizerr "github.com/tidbcloud/infra-provider/regional-server/pkg/common/errors"
)

// FromRequest returns the ownership asserted by the request. An absent or empty
// context preserves the existing ownerless behavior.
func FromRequest(context *regionalapiv1.ResourceOwnershipContext) *v1alpha1.ResourceOwnership {
	if context == nil || context.SharedPoolId == "" {
		return nil
	}
	return &v1alpha1.ResourceOwnership{SharedPoolID: context.SharedPoolId}
}

// Match verifies ownership only when the persisted resource has an owner.
// Ownerless resources remain compatible with requests with or without context.
func Match(context *regionalapiv1.ResourceOwnershipContext, current *v1alpha1.ResourceOwnership) error {
	if current == nil || current.SharedPoolID == "" {
		return nil
	}
	if context == nil || context.SharedPoolId != current.SharedPoolID {
		return bizerr.New(bizerr.ResourceConflict, "resource ownership does not match")
	}
	return nil
}
