package automation

import (
	"context"

	"github.com/nexuscrm/shared/pkg/constants"
)

// withConnectorInboundCompanionSubflowDelegation replaces any inherited grant
// at every native Subflow boundary. Only an exact, worker-authorized companion
// version can mint a grant, and the grant is bound to the directly declared
// child name and the parent's owner pack.
func withConnectorInboundCompanionSubflowDelegation(ctx context.Context, childFlowAPIName string) context.Context {
	frc := flowRuntimeContextFromCtx(ctx)
	delegated := frc.withConnectorInboundCompanionSubflowDelegation("", "")
	parentIdentity, ok := frc.CurrentFlow()
	if ok && flowIdentityIsPackOwnedStandard(parentIdentity) &&
		constants.ConnectorInboundCompanionExecutionAuthorizesVersion(ctx, parentIdentity.VersionID) {
		delegated = frc.withConnectorInboundCompanionSubflowDelegation(childFlowAPIName, parentIdentity.OwnerPack)
	}
	return withFlowRuntimeContext(ctx, delegated)
}

// connectorInboundCompanionSubflowExecutionAuthorized verifies the consuming
// child's trusted runtime identity. The caller must still enforce the specific
// privileged operation's own guards (for example, an atomic transaction).
func connectorInboundCompanionSubflowExecutionAuthorized(ctx context.Context, identity FlowExecutionIdentity) bool {
	return flowIdentityIsPackOwnedStandard(identity) &&
		flowRuntimeContextFromCtx(ctx).connectorInboundCompanionSubflowAuthorizes(identity)
}
