package tidbupgrader

import (
	"strings"

	"github.com/tidbcloud/aws-shared-provider/pkg/types"
	"k8s.io/utils/ptr"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

func (tu *TidbUpgrader) handleOldAbnormal() {
	abnormalList, err := tu.pool.GetAbnormalPodList(tu.ctx)
	if err != nil {
		tu.Error(err, "get abnormal tidb pod list")
		return
	}
	for i := 0; i < len(abnormalList); i++ {
		if !strings.HasPrefix(abnormalList[i].Name, types.TidbServerNamePrefix+tu.tidbPool.Revision) {
			// abnormal old revision tidb pod
			err := tu.client.Delete(tu.ctx, &abnormalList[i], &client.DeleteOptions{GracePeriodSeconds: ptr.To[int64](0)})
			if err == nil {
				tu.Info("[pod lifecycle] delete abnormal old revision tidb pod", "pod name", abnormalList[i].Name)
			}
			if err = client.IgnoreNotFound(err); err != nil {
				tu.Error(err, "delete abnormal old revision tidb pod", "pod name", abnormalList[i].Name)
			}
		}
	}
}
