package tidbreclaimer

import (
	"fmt"
	"strconv"
	"time"

	"github.com/pingcap/errors"
)

func (tr *TidbReclaimer) QueryInactivePods() ([]string, error) {
	if tr.o11yQuerier == nil {
		return nil, errors.New("the querier is nil")
	}

	base10 := 10
	queryRange := tr.gcInterval.String()
	v := map[string]string{
		"query": fmt.Sprintf(`sum by(instance) (changes(up{component="tidb",namespace="%s"}[%s])==0`+
			`and up{component="tidb",namespace="%s"}==0)`, tr.tidbPoolNamespace, queryRange, tr.tidbPoolNamespace),
		"_": strconv.FormatInt(time.Now().Unix(), base10), // a dummy value just avoid cache
	}

	resp, err := tr.o11yQuerier.QueryMetrics(tr.ctx, "/api/v1/query", v)
	if err != nil {
		return nil, err
	}

	resLen := len(resp.Data.Result)
	if resLen <= 0 {
		return nil, nil
	}

	res := make([]string, resLen)
	for i, r := range resp.Data.Result {
		res[i] = r.Metric["instance"]
	}

	return res, nil
}
