package balance

import (
	"testing"
	"time"

	frostfscontract "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client/frostfs"
	balanceEvent "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/event/balance"
	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/util/logger/test"
	"github.com/nspcc-dev/neo-go/pkg/util"
	"github.com/stretchr/testify/require"
)

func TestProcessorCallsFrostFSContractForLockEvent(t *testing.T) {
	t.Parallel()
	as := &testAlphabetState{
		isAlphabet: true,
	}
	conv := &testPresicionConverter{}
	cl := &testFrostFSContractClient{}
	bsc := util.Uint160{100}

	processor, err := New(&Params{
		Log:           test.NewLogger(t),
		PoolSize:      2,
		FrostFSClient: cl,
		BalanceSC:     bsc,
		AlphabetState: as,
		Converter:     conv,
	})
	require.NoError(t, err, "failed to create processor")

	processor.handleLock(balanceEvent.Lock{})

	for processor.pool.Running() > 0 {
		time.Sleep(10 * time.Millisecond)
	}

	require.Equal(t, 1, cl.chequeCalls, "invalid Cheque calls")
}

func TestProcessorDoesntCallFrostFSContractIfNotAlphabet(t *testing.T) {
	t.Parallel()
	as := &testAlphabetState{}
	conv := &testPresicionConverter{}
	cl := &testFrostFSContractClient{}
	bsc := util.Uint160{100}

	processor, err := New(&Params{
		Log:           test.NewLogger(t),
		PoolSize:      2,
		FrostFSClient: cl,
		BalanceSC:     bsc,
		AlphabetState: as,
		Converter:     conv,
	})
	require.NoError(t, err, "failed to create processor")

	processor.handleLock(balanceEvent.Lock{})

	for processor.pool.Running() > 0 {
		time.Sleep(10 * time.Millisecond)
	}

	require.Equal(t, 0, cl.chequeCalls, "invalid Cheque calls")
}

type testAlphabetState struct {
	isAlphabet bool
}

func (s *testAlphabetState) IsAlphabet() bool {
	return s.isAlphabet
}

type testPresicionConverter struct{}

func (c *testPresicionConverter) ToFixed8(v int64) int64 {
	return v
}

type testFrostFSContractClient struct {
	chequeCalls int
}

func (c *testFrostFSContractClient) Cheque(p frostfscontract.ChequePrm) error {
	c.chequeCalls++
	return nil
}