package types

import (
	"encoding/hex"
	"math/rand"
	"strings"
	"testing"
	"time"

	"cosmossdk.io/math"
	"github.com/stretchr/testify/assert"

	"github.com/bnb-chain/greenfield/types/resource"
)

func TestParsePolicyIdFromQueueKey(t *testing.T) {
	for i := 0; i < 100; i++ {
		expiration := time.Now().Add(time.Duration(rand.Int63()))
		policyId := math.NewUint(rand.Uint64())
		key := PolicyPrefixQueue(&expiration, policyId.Bytes())
		recoverId := ParsePolicyIdFromQueueKey(key)
		if !recoverId.Equal(policyId) {
			t.Errorf("ParseIdFromQueueKey failed to recover policy id: %s", policyId.String())
		}
	}
}
func TestPrefixKeyCollision(t *testing.T) {
	resourceID1 := math.NewUint(17)
	resourceID2 := math.NewUint(4522)

	// collision, the prefix bytes of resourceID2 has included all prefix bytes generated by resourceID1
	assert.True(t, strings.Contains(
		hex.EncodeToString(PolicyForAccountPrefix(resourceID2, resource.RESOURCE_TYPE_BUCKET, false)),
		hex.EncodeToString(PolicyForAccountPrefix(resourceID1, resource.RESOURCE_TYPE_BUCKET, false)),
	))

	assert.False(t, strings.Contains(
		hex.EncodeToString(PolicyForAccountPrefix(resourceID2, resource.RESOURCE_TYPE_BUCKET, true)),
		hex.EncodeToString(PolicyForAccountPrefix(resourceID1, resource.RESOURCE_TYPE_BUCKET, true)),
	))
}
