package request

import (
	"fmt"
	"strconv"
	"strings"

	frostfsidcore "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/core/frostfsid"
	apechain "git.frostfs.info/TrueCloudLab/policy-engine/pkg/chain"
	commonschema "git.frostfs.info/TrueCloudLab/policy-engine/schema/common"
	"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
)

// FormFrostfsIDRequestProperties forms frostfsid specific request properties like user-claim tags and group ID.
func FormFrostfsIDRequestProperties(frostFSIDClient frostfsidcore.SubjectProvider, pk *keys.PublicKey) (map[string]string, error) {
	reqProps := make(map[string]string)
	subj, err := frostFSIDClient.GetSubjectExtended(pk.GetScriptHash())
	if err != nil {
		if !strings.Contains(err.Error(), frostfsidcore.SubjectNotFoundErrorMessage) {
			return nil, fmt.Errorf("get subject error: %w", err)
		}
		return reqProps, nil
	}
	for k, v := range subj.KV {
		propertyKey := fmt.Sprintf(commonschema.PropertyKeyFormatFrostFSIDUserClaim, k)
		reqProps[propertyKey] = v
	}

	groups := make([]string, len(subj.Groups))
	for i, group := range subj.Groups {
		groups[i] = strconv.FormatInt(group.ID, 10)
	}
	reqProps[commonschema.PropertyKeyFrostFSIDGroupID] = apechain.FormCondSliceContainsValue(groups)

	return reqProps, nil
}

// Groups return the actor's group ids from frostfsid contract.
func Groups(frostFSIDClient frostfsidcore.SubjectProvider, pk *keys.PublicKey) ([]string, error) {
	subj, err := frostFSIDClient.GetSubjectExtended(pk.GetScriptHash())
	if err != nil {
		if !strings.Contains(err.Error(), frostfsidcore.SubjectNotFoundErrorMessage) {
			return nil, fmt.Errorf("get subject error: %w", err)
		}
		return []string{}, nil
	}
	groups := make([]string, len(subj.Groups))
	for i, group := range subj.Groups {
		groups[i] = strconv.FormatInt(group.ID, 10)
	}
	return groups, nil
}