package store

import (
	"testing"

	"github.com/pingcap/test-infra/services/tcms/service/internalrpc"
	"github.com/pingcap/test-infra/services/tcms/tests"
	"github.com/pingcap/test-infra/services/tcms/tests/configtest"
)

func setup(t *testing.T, opts ...configtest.Option) *TestStore {
	cfg := configtest.NewTestConfig(t, opts...)
	tests.Setup(t, cfg)
	return NewTestStore(t, cfg)
}

func NewTestStore(t *testing.T, cfg *configtest.Config) *TestStore {
	return &TestStore{
		Store: New(cfg.Config, internalrpc.NewRMSRPCService()),
		t:     t,
		cfg:   cfg,
	}
}

type TestStore struct {
	*Store
	t   *testing.T
	cfg *configtest.Config
}

func (s *TestStore) Shutdown() (err error) {
	if err = s.Store.Shutdown(); err != nil {
		return
	}

	succeed := !s.t.Failed()
	if succeed {
		// If test is success, drop the test database.
		err = tests.DropDB(s.cfg.DSN)
	}
	return
}
