package nodepoolgc

import (
	"testing"
	"time"

	"github.com/stretchr/testify/require"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"

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

func TestRefreshUsage(t *testing.T) {
	now := time.Date(2026, 7, 10, 8, 0, 0, 0, time.UTC)
	previous := now.Add(-time.Hour).Format(time.RFC3339)
	approved := now.Add(-2 * time.Hour).Format(time.RFC3339)
	lastUsed := now.Add(-30 * time.Second).Format(time.RFC3339)
	tests := []struct {
		name           string
		annotations    map[string]string
		managed        bool
		wantLastUsed   string
		wantApprovedAt string
	}{
		{
			name: "refreshes stale usage and clears expiration mark",
			annotations: map[string]string{
				consts.AnnoKeyNodePoolLastUsedTime: previous,
				consts.AnnoKeyNodePoolGCExpiredAt:  previous,
				consts.AnnoKeyNodePoolGCApprovedAt: approved,
			},
			wantLastUsed:   now.Format(time.RFC3339),
			wantApprovedAt: approved,
		},
		{
			name:         "initializes a pool without usage metadata",
			wantLastUsed: now.Format(time.RFC3339),
		},
		{
			name: "respects the refresh cooldown while clearing expiration mark",
			annotations: map[string]string{
				consts.AnnoKeyNodePoolLastUsedTime: lastUsed,
				consts.AnnoKeyNodePoolGCExpiredAt:  previous,
			},
			managed:      true,
			wantLastUsed: lastUsed,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			obj := &unstructured.Unstructured{}
			obj.SetAnnotations(tt.annotations)
			if tt.managed {
				obj.SetLabels(map[string]string{
					consts.LabelKeyNodePoolGCManaged: consts.AnnoValTrue,
				})
			}

			RefreshUsage(obj, now)

			require.Equal(t, consts.AnnoValTrue, obj.GetLabels()[consts.LabelKeyNodePoolGCManaged])
			require.Equal(t, tt.wantLastUsed, obj.GetAnnotations()[consts.AnnoKeyNodePoolLastUsedTime])
			require.Equal(t, tt.wantApprovedAt, obj.GetAnnotations()[consts.AnnoKeyNodePoolGCApprovedAt])
			require.NotContains(t, obj.GetAnnotations(), consts.AnnoKeyNodePoolGCExpiredAt)
			require.NotContains(t, obj.GetAnnotations(), consts.AnnoKeyNodePoolGCLastScanAt)
		})
	}
}
