package simulation_test

import (
	"encoding/binary"
	"fmt"
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/cosmos/cosmos-sdk/types/kv"

	"github.com/provenance-io/provenance/app"
	"github.com/provenance-io/provenance/x/attribute/simulation"
	"github.com/provenance-io/provenance/x/attribute/types"
)

func TestDecodeStore(t *testing.T) {
	cdc := app.MakeTestEncodingConfig(t).Marshaler
	dec := simulation.NewDecodeStore(cdc)

	testAttributeRecord := types.NewAttribute("test", "", types.AttributeType_Int, []byte{1}, nil, "")
	testParams := types.DefaultParams()

	countBz := make([]byte, 8)
	binary.BigEndian.PutUint64(countBz, 3)

	kvPairs := kv.Pairs{
		Pairs: []kv.Pair{
			{Key: types.AttributeKeyPrefix, Value: cdc.MustMarshal(&testAttributeRecord)},
			{Key: types.AttributeAddrLookupKeyPrefix, Value: countBz},
			{Key: types.AttributeExpirationKeyPrefix, Value: []byte{}},
			{Key: types.AttributeParamPrefix, Value: cdc.MustMarshal(&testParams)},
			{Key: []byte{0x99}, Value: []byte{0x99}},
		},
	}

	tests := []struct {
		attribute   string
		expectedLog string
	}{
		{"Attribute Record", fmt.Sprintf("%v\n%v", testAttributeRecord, testAttributeRecord)},
		{"AddrLookup Count", fmt.Sprintf("%d\n%d", uint64(3), uint64(3))},
		{"Expiration", fmt.Sprintf("%X\n%X", []byte{}, []byte{})},
		{"Params", fmt.Sprintf("%v\n%v", testParams, testParams)},
		{"other", ""},
	}

	for i, tt := range tests {
		t.Run(tt.attribute, func(t *testing.T) {
			switch i {
			case len(tests) - 1:
				require.Panics(t, func() { dec(kvPairs.Pairs[i], kvPairs.Pairs[i]) }, tt.attribute)
			default:
				require.Equal(t, tt.expectedLog, dec(kvPairs.Pairs[i], kvPairs.Pairs[i]), tt.attribute)
			}
		})
	}
}
