package nodepoolgc

import (
	"context"

	"github.com/pingcap/errors"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/selection"
	"sigs.k8s.io/controller-runtime/pkg/client"

	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
	"github.com/tidbcloud/infra-provider/pkg/consts"
	"github.com/tidbcloud/infra-provider/pkg/namer"
)

// ListBRNodePools lists Dedicated customer workload nodepools used by Backup,
// Restore, or CompactBackup.
func ListBRNodePools(ctx context.Context, local client.Client, list client.ObjectList) error {
	selector, err := buildListBRNodePoolsSelector()
	if err != nil {
		return err
	}
	return local.List(ctx, list, client.MatchingLabelsSelector{Selector: selector})
}

func buildListBRNodePoolsSelector() (labels.Selector, error) {
	component, err := labels.NewRequirement(
		namer.ComponentSelectorKey,
		selection.In,
		[]string{
			string(cloudv1.ComponentBackup),
			string(cloudv1.ComponentRestore),
			string(cloudv1.ComponentCompactBackup),
		},
	)
	if err != nil {
		return nil, errors.Wrap(err, "cannot build BR nodepool component selector")
	}
	selector := labels.Set{
		consts.TagKeyServiceType: consts.ServiceTypeDedicated,
		consts.TagKeyUsedBy:      consts.UsedByCustomerTiDB,
	}.AsSelectorPreValidated().Add(*component)
	return selector, nil
}
