package nodepoolgc

import (
	"time"

	"sigs.k8s.io/controller-runtime/pkg/client"

	"github.com/tidbcloud/infra-provider/pkg/consts"
)

const usageRefreshCooldown = time.Minute

// RefreshUsage updates the metadata written by nodepool tasks. The last-used
// timestamp is rate limited to avoid an API write on every reconciliation.
func RefreshUsage(obj client.Object, now time.Time) {
	labels := obj.GetLabels()
	if labels == nil {
		labels = map[string]string{}
	}
	if _, ok := labels[consts.LabelKeyNodePoolGCManaged]; !ok {
		labels[consts.LabelKeyNodePoolGCManaged] = consts.AnnoValTrue
	}
	obj.SetLabels(labels)

	annotations := obj.GetAnnotations()
	if annotations == nil {
		annotations = map[string]string{}
	}

	now = now.UTC()
	lastUsed, err := time.Parse(time.RFC3339, annotations[consts.AnnoKeyNodePoolLastUsedTime])
	if err != nil || !now.Before(lastUsed.Add(usageRefreshCooldown)) {
		annotations[consts.AnnoKeyNodePoolLastUsedTime] = now.Format(time.RFC3339)
	}
	delete(annotations, consts.AnnoKeyNodePoolGCExpiredAt)
	obj.SetAnnotations(annotations)
}
