package task

import (
	"context"
	"testing"

	vmoperatorv1beta1 "github.com/VictoriaMetrics/operator/api/operator/v1beta1"
	"github.com/stretchr/testify/assert"
	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/utils/ptr"
	"sigs.k8s.io/controller-runtime/pkg/client"

	agentv2 "github.com/tidbcloud/observability/agent-control-server/api/v2"
	"github.com/tidbcloud/observability/agent-control-server/pkg/config"
	"github.com/tidbcloud/observability/agent-control-server/pkg/consts"
	"github.com/tidbcloud/observability/agent-control-server/pkg/reconciler"
	"github.com/tidbcloud/observability/agent-control-server/pkg/testkits"
)

func makeVMAgentTask(agent *agentv2.O11yTiDBAgent, opts testkits.TaskOptions) *VMAgentTask {
	objs := []client.Object{agent}
	if len(opts.LocalObjects) > 0 {
		objs = append(objs, opts.LocalObjects...)
	}
	localCli := testkits.BuildClient(objs...)

	ctx := &reconciler.Context[*agentv2.O11yTiDBAgent]{
		Agent:     agent,
		Local:     localCli,
		Remote:    testkits.NewClientGetterWithOpts(opts),
		Config:    &opts.Config,
		Templates: opts.Templates,
	}
	return NewVMAgentTask(ctx)
}

func baseVMAgentConfig() config.RootConfig {
	return config.RootConfig{
		O11yConfig: config.ObservabilityInfra{
			Vendor: "aws",
			CustomerConfigsV2: config.CustomerConfigsV2{
				Dedicated: config.CustomerDedicated{
					TiDBCluster: config.CustomerDedicatedTiDBCluster{
						Default: config.CustomerAgents{
							VMAgent: &config.VMAgentConfig{
								Image: "victoriametrics/vmagent:latest",
								StatefulStorage: &vmoperatorv1beta1.StorageSpec{
									VolumeClaimTemplate: vmoperatorv1beta1.EmbeddedPersistentVolumeClaim{
										Spec: corev1.PersistentVolumeClaimSpec{},
									},
								},
							},
						},
					},
					Specs: config.CustomerDedicatedSpecs{
						TiDBCluster: config.CustomerAgentSpecs{
							{
								Name:    "default",
								VMAgent: &corev1.ResourceRequirements{},
							},
						},
					},
				},
			},
		},
	}
}

func TestVMAgentTask(t *testing.T) {
	tests := []struct {
		name   string
		verify func(t *testing.T)
	}{
		{
			name: "Name",
			verify: func(t *testing.T) {
				task := &VMAgentTask{}
				assert.Equal(t, "VMAgent", task.Name())
			},
		},
		{
			name: "ClusterMeta",
			verify: func(t *testing.T) {
				agent := testkits.NewO11yTiDBAgentBuilder().Build()
				task := makeVMAgentTask(agent, testkits.TaskOptions{})
				meta := task.ClusterMeta()

				assert.Equal(t, consts.AgentO11yTidb, meta.Agent)
				assert.Equal(t, "test-cluster", meta.K8sClusterName)
				assert.Equal(t, "tenant-1", meta.TenantID)
				assert.Equal(t, "app-1", meta.ApplicationID)
				assert.Equal(t, "tidbcloud", meta.BizType)
			},
		},
		{
			name: "buildNamespace",
			verify: func(t *testing.T) {
				agent := testkits.NewO11yTiDBAgentBuilder().Build()
				task := makeVMAgentTask(agent, testkits.TaskOptions{})
				assert.Equal(t, "tidbapp-1", task.buildNamespace())
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			tt.verify(t)
		})
	}
}

func TestVMAgentTask_Create(t *testing.T) {
	tests := []struct {
		name    string
		agent   *agentv2.O11yTiDBAgent
		opts    testkits.TaskOptions
		wantErr bool
	}{
		{
			name:    "create fails with remote client error",
			agent:   testkits.NewO11yTiDBAgentBuilder().Build(),
			opts:    testkits.TaskOptions{ClientError: true, Config: baseVMAgentConfig()},
			wantErr: true,
		},
		{
			name:    "create fails with missing template",
			agent:   testkits.NewO11yTiDBAgentBuilder().Build(),
			opts:    testkits.TaskOptions{Client: testkits.BuildClient(), Config: baseVMAgentConfig()},
			wantErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			task := makeVMAgentTask(tt.agent, tt.opts)
			result := task.Create(context.Background())
			if tt.wantErr {
				assert.Error(t, result.Error())
			} else {
				assert.NoError(t, result.Error())
			}
		})
	}
}

func TestVMAgentTask_PostCreate(t *testing.T) {
	tests := []struct {
		name    string
		agent   *agentv2.O11yTiDBAgent
		opts    testkits.TaskOptions
		wantErr bool
	}{
		{
			name:    "post create fails with remote client error",
			agent:   testkits.NewO11yTiDBAgentBuilder().Build(),
			opts:    testkits.TaskOptions{ClientError: true},
			wantErr: true,
		},
		{
			name:    "post create fails when statefulset not ready",
			agent:   testkits.NewO11yTiDBAgentBuilder().Build(),
			opts:    testkits.TaskOptions{Client: testkits.BuildClient()},
			wantErr: true,
		},
		{
			name:  "post create succeeds when statefulset ready",
			agent: testkits.NewO11yTiDBAgentBuilder().Build(),
			opts: testkits.TaskOptions{
				Client: testkits.BuildClient(
					&appsv1.StatefulSet{
						ObjectMeta: metav1.ObjectMeta{
							Name:      vmagentStsName,
							Namespace: "tidbapp-1",
						},
						Spec:   appsv1.StatefulSetSpec{Replicas: ptr.To(int32(1))},
						Status: appsv1.StatefulSetStatus{AvailableReplicas: 1},
					},
				),
			},
			wantErr: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			task := makeVMAgentTask(tt.agent, tt.opts)
			result := task.PostCreate(context.Background())
			if tt.wantErr {
				assert.Error(t, result.Error())
			} else {
				assert.NoError(t, result.Error())
			}
		})
	}
}

func TestVMAgentTask_Delete(t *testing.T) {
	tests := []struct {
		name    string
		agent   *agentv2.O11yTiDBAgent
		opts    testkits.TaskOptions
		wantErr bool
	}{
		{
			name:  "delete fails with remote client error",
			agent: testkits.NewO11yTiDBAgentBuilder().Build(),
			opts: testkits.TaskOptions{
				ClientError: true,
				Config:      baseVMAgentConfig(),
			},
			wantErr: true,
		},
		{
			name:  "delete succeeds with valid remote client",
			agent: testkits.NewO11yTiDBAgentBuilder().Build(),
			opts: testkits.TaskOptions{
				Client: testkits.BuildClient(),
				Config: baseVMAgentConfig(),
			},
			wantErr: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			task := makeVMAgentTask(tt.agent, tt.opts)
			result := task.Delete(context.Background())
			if tt.wantErr {
				assert.Error(t, result.Error())
			} else {
				assert.NoError(t, result.Error())
			}
		})
	}
}

func TestVMAgentTask_PostDelete(t *testing.T) {
	tests := []struct {
		name    string
		agent   *agentv2.O11yTiDBAgent
		opts    testkits.TaskOptions
		wantErr bool
	}{
		{
			name:    "post delete fails with remote client error",
			agent:   testkits.NewO11yTiDBAgentBuilder().Build(),
			opts:    testkits.TaskOptions{ClientError: true},
			wantErr: true,
		},
		{
			name:    "post delete succeeds when statefulset deleted",
			agent:   testkits.NewO11yTiDBAgentBuilder().Build(),
			opts:    testkits.TaskOptions{Client: testkits.BuildClient()},
			wantErr: false,
		},
		{
			name:  "post delete fails when statefulset still exists",
			agent: testkits.NewO11yTiDBAgentBuilder().Build(),
			opts: testkits.TaskOptions{
				Client: testkits.BuildClient(
					&appsv1.StatefulSet{
						ObjectMeta: metav1.ObjectMeta{
							Name:      vmagentStsName,
							Namespace: "tidbapp-1",
						},
					},
				),
			},
			wantErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			task := makeVMAgentTask(tt.agent, tt.opts)
			result := task.PostDelete(context.Background())
			if tt.wantErr {
				assert.Error(t, result.Error())
			} else {
				assert.NoError(t, result.Error())
			}
		})
	}
}
