package scheduled

import (
	"testing"

	"github.com/hashicorp/go-multierror"

	"github.com/pingcap/test-infra/services/tcms/handler"
	"github.com/pingcap/test-infra/services/tcms/tests"
	"github.com/pingcap/test-infra/services/tcms/tests/configtest"
	"github.com/pingcap/test-infra/services/tcms/utils/sql"
)

func setup(t *testing.T, opts ...configtest.Option) (db *sql.Database, svc *handler.HandlerService) {
	cfg := configtest.NewTestConfig(t, opts...)
	tests.Setup(t, cfg)
	db = sql.MustConnect(cfg.DSN)
	svc = handler.NewHandlerService(cfg.Config)
	// drop test db if success
	origShutdown := svc.Shutdown
	svc.Shutdown = func() (errs error) {
		if err := origShutdown(); err != nil {
			multierror.Append(errs, err)
		}
		succeed := !t.Failed()
		if succeed {
			if err := tests.DropDB(cfg.DSN); err != nil {
				multierror.Append(errs, err)
			}
		}
		return
	}
	return
}

func shotdown(db *sql.Database, svc *handler.HandlerService) (errs error) {
	if err := db.Close(); err != nil {
		errs = multierror.Append(errs, err)
	}
	if err := svc.Shutdown(); err != nil {
		errs = multierror.Append(errs, err)
	}
	return
}
