package simulation_test

import (
	"fmt"
	"testing"
	"time"

	"github.com/stretchr/testify/require"

	"git.cw.tr/mukan-network/mukan-sdk/types/kv"

	"git.cw.tr/mukan-network/mukan-ibc/modules/core/02-client/simulation"
	"git.cw.tr/mukan-network/mukan-ibc/modules/core/02-client/types"
	host "git.cw.tr/mukan-network/mukan-ibc/modules/core/24-host"
	ibctm "git.cw.tr/mukan-network/mukan-ibc/modules/light-clients/07-tendermint"
	"git.cw.tr/mukan-network/mukan-ibc/testing/simapp"
)

func TestDecodeStore(t *testing.T) {
	app := simapp.Setup(t, false)
	clientID := "clientidone"

	height := types.NewHeight(0, 10)

	clientState := &ibctm.ClientState{
		FrozenHeight: height,
	}

	consState := &ibctm.ConsensusState{
		Timestamp: time.Now().UTC(),
	}

	kvPairs := kv.Pairs{
		Pairs: []kv.Pair{
			{
				Key:   host.FullClientStateKey(clientID),
				Value: types.MustMarshalClientState(app.AppCodec(), clientState),
			},
			{
				Key:   host.FullConsensusStateKey(clientID, height),
				Value: types.MustMarshalConsensusState(app.AppCodec(), consState),
			},
			{
				Key:   []byte{0x99},
				Value: []byte{0x99},
			},
		},
	}
	tests := []struct {
		name        string
		expectedLog string
	}{
		{"ClientState", fmt.Sprintf("ClientState A: %v\nClientState B: %v", clientState, clientState)},
		{"ConsensusState", fmt.Sprintf("ConsensusState A: %v\nConsensusState B: %v", consState, consState)},
		{"other", ""},
	}

	for i, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			res, found := simulation.NewDecodeStore(app.AppCodec(), kvPairs.Pairs[i], kvPairs.Pairs[i])
			if i == len(tests)-1 {
				require.False(t, found, string(kvPairs.Pairs[i].Key))
				require.Empty(t, res, string(kvPairs.Pairs[i].Key))
			} else {
				require.True(t, found, string(kvPairs.Pairs[i].Key))
				require.Equal(t, tt.expectedLog, res, string(kvPairs.Pairs[i].Key))
			}
		})
	}
}
