package hook

import (
	"context"

	"github.com/tidbcloud/pov-service/internal/gateway"
	"github.com/tidbcloud/pov-service/internal/model"
	"github.com/tidbcloud/pov-service/internal/pkg/log"
)

type ReleaseCluster struct {
	gateway gateway.Workload
}

func NewReleaseCluster(workload gateway.Workload) ReleaseCluster {
	return ReleaseCluster{
		gateway: workload,
	}
}

func (r ReleaseCluster) Match(
	from model.WorkloadTestPhase,
	to model.WorkloadTestPhase,
	test model.WorkloadTest) bool {
	if test.Cluster == nil {
		return false
	}
	return to == model.WorkloadTestPhaseFinished
}

func (r ReleaseCluster) Do(ctx context.Context, test model.WorkloadTest) error {
	log.Log.Infof("Delete cluster for test %s", test.ID)
	if err := r.gateway.ReleaseCluster(ctx, *test.Cluster); err != nil {
		log.Log.Errorf(err, "delete cluster failed")
		return err
	}

	return nil
}

func (r ReleaseCluster) GetName() string {
	return "release_cluster_hook"
}
