package runtimeapi

import (
	"context"
	"errors"

	"github.com/pingcap-inc/nexuscrm-api-host/runtimegrpc"
	approvalnotificationsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/approvalnotificationflowv1"
	"google.golang.org/grpc"
)

// ApprovalNotificationFlowReadSelection is deployment-owned workload
// admission. It selects no Catalog handler, projection, or executable Flow
// authority.
type ApprovalNotificationFlowReadSelection struct {
	OrgID             string
	AppInstallationID string
	WorkloadID        string
}

// ApprovalNotificationFlowReadAdmission binds the neutral descriptor read to
// the exact application workload authorized by deployment.
type ApprovalNotificationFlowReadAdmission struct {
	selection ApprovalNotificationFlowReadSelection
}

func NewApprovalNotificationFlowReadAdmission(
	selection ApprovalNotificationFlowReadSelection,
) (*ApprovalNotificationFlowReadAdmission, error) {
	if selection.OrgID == "" || selection.AppInstallationID == "" || selection.WorkloadID == "" {
		return nil, errors.New("approval notification Flow read admission requires org, installation, and workload")
	}
	return &ApprovalNotificationFlowReadAdmission{selection: selection}, nil
}

func (admission *ApprovalNotificationFlowReadAdmission) UnaryServerInterceptor() grpc.UnaryServerInterceptor {
	return func(
		ctx context.Context,
		request any,
		_ *grpc.UnaryServerInfo,
		handler grpc.UnaryHandler,
	) (any, error) {
		capability, ok := runtimegrpc.Capability(ctx)
		if !ok || capability != approvalnotificationsemantic.CapabilityName {
			return handler(ctx, request)
		}
		admitted, err := admission.bind(ctx)
		if err != nil {
			return nil, runtimegrpc.StatusError(ctx, err)
		}
		return handler(admitted, request)
	}
}

func (admission *ApprovalNotificationFlowReadAdmission) bind(ctx context.Context) (context.Context, error) {
	trusted, ok := trustedCallFromContext(ctx)
	if !ok {
		return nil, &approvalnotificationsemantic.Failure{
			Category: approvalnotificationsemantic.FailureUnauthenticated,
		}
	}
	if admission == nil || trusted.orgID != admission.selection.OrgID ||
		trusted.appInstallationID != admission.selection.AppInstallationID ||
		trusted.callerWorkloadID != admission.selection.WorkloadID {
		return nil, &approvalnotificationsemantic.Failure{
			Category: approvalnotificationsemantic.FailureForbidden,
		}
	}
	return ctx, nil
}
