package permissions

import (
	"context"
	"strings"

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

// isApprovalLockedForOperation enforces pending-approval record editability.
// The lock is dynamic: records are considered locked while a ProcessInstance is
// pending, and automatically unlock once the instance leaves Pending.
func (ps *PermissionService) isApprovalLockedForOperation(ctx context.Context, record models.SObject, operation string, user *models.UserSession) bool {
	if operation == constants.PermRead || user == nil || ps.repo == nil || canBypassApprovalLock(ctx, user) {
		return false
	}

	recordID, _ := record[constants.FieldID].(string)
	if strings.TrimSpace(recordID) == "" {
		return false
	}

	processInstanceID, lockType, err := ps.repo.GetPendingApprovalLockInfo(ctx, recordID)
	if err != nil || strings.TrimSpace(lockType) == "" {
		return false
	}

	switch strings.ToLower(strings.TrimSpace(lockType)) {
	case "workitem":
		if strings.TrimSpace(processInstanceID) == "" {
			return true
		}
		hasWorkitem, workitemErr := ps.repo.HasPendingApprovalWorkitemForUser(ctx, processInstanceID, user.ID)
		if workitemErr != nil {
			return true
		}
		return !hasWorkitem
	case "admin":
		return true
	default:
		return true
	}
}
