package clusterconfig

import (
	"reflect"
	"testing"
	"time"

	"github.com/golang/mock/gomock"
	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
	"github.com/tidbcloud/infra-provider/pkg/gitops-sdk/revision/mock_revision"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
)

func TestGetLastCreatedConfigRevision(t *testing.T) {
	cr1 := cloudv1.ConfigRevision{}
	cr1.CreationTimestamp = metav1.NewTime(time.Unix(1000, 0))
	cr2 := cloudv1.ConfigRevision{}
	cr2.CreationTimestamp = metav1.NewTime(time.Unix(2000, 0))
	clusterName := "c1"
	lbl := map[string]string{
		cloudv1.ClusterTagKey: clusterName,
	}

	tests := []struct {
		name    string
		crs     []cloudv1.ConfigRevision
		want    *cloudv1.ConfigRevision
		wantErr bool
	}{
		{
			name:    "return empty cr if crs is empty",
			crs:     nil,
			want:    &cloudv1.ConfigRevision{},
			wantErr: false,
		},
		{
			name:    "return itself if only one",
			crs:     []cloudv1.ConfigRevision{cr1},
			want:    &cr1,
			wantErr: false,
		},
		{
			name:    "return last one if have more than one",
			crs:     []cloudv1.ConfigRevision{cr1, cr2},
			want:    &cr2,
			wantErr: false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			ctrl := gomock.NewController(t)
			defer ctrl.Finish()
			revision := mock_revision.NewMockInterface(ctrl)

			revision.EXPECT().ListConfigRevisions(labels.SelectorFromSet(lbl)).Return(tt.crs, nil)

			got, err := GetLastCreatedConfigRevision(revision, clusterName)
			if (err != nil) != tt.wantErr {
				t.Errorf("GetLastCreatedConfigRevision() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf("GetLastCreatedConfigRevision() got = %v, want %v", got, tt.want)
			}
		})
	}
}
