package task

import (
	"context"
	"testing"
	"text/template"

	vmoperatorv1beta1 "github.com/VictoriaMetrics/operator/api/operator/v1beta1"
	"github.com/stretchr/testify/assert"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	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 makeServerlessVMPodScrapeTask(agent *agentv2.SharedPoolAgent, opts testkits.TaskOptions) *ServerlessVMPodScrapeTask {
	ctx := &reconciler.Context[*agentv2.SharedPoolAgent]{
		Agent:     agent,
		Local:     testkits.BuildClient(agent),
		Remote:    testkits.NewClientGetterWithOpts(opts),
		Config:    &config.RootConfig{},
		Templates: opts.Templates,
	}
	return NewServerlessVMPodScrapeTask(ctx)
}

func TestServerlessVMPodScrapeTask(t *testing.T) {
	tests := []struct {
		name   string
		verify func(t *testing.T)
	}{
		{
			name: "Name",
			verify: func(t *testing.T) {
				task := &ServerlessVMPodScrapeTask{}
				assert.Equal(t, "VMPodScrape", task.Name())
			},
		},
		{
			name: "ClusterMeta",
			verify: func(t *testing.T) {
				agent := testkits.NewSharedPoolAgentBuilder().Build()
				task := makeServerlessVMPodScrapeTask(agent, testkits.TaskOptions{})
				meta := task.ClusterMeta()

				assert.Equal(t, consts.AgentSharedPool, meta.Agent)
				assert.Equal(t, "test-cluster", meta.K8sClusterName)
				assert.Equal(t, "tenant-1", meta.TenantID)
				assert.Equal(t, "app-1", meta.ApplicationID)
			},
		},
		{
			name: "buildNamespace returns serverless namespace",
			verify: func(t *testing.T) {
				agent := testkits.NewSharedPoolAgentBuilder().Build()
				task := makeServerlessVMPodScrapeTask(agent, testkits.TaskOptions{})
				assert.Equal(t, consts.ServerlessObservabilityNamespace, task.buildNamespace())
			},
		},
	}

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

func TestServerlessVMPodScrapeTask_Create(t *testing.T) {
	tmpl, err := template.New("test").Parse(`
metadata:
  name: test-multitenant
  namespace: {{.Namespace}}
spec:
  selector: {}
`)
	assert.NoError(t, err)

	tests := []struct {
		name    string
		agent   *agentv2.SharedPoolAgent
		opts    testkits.TaskOptions
		wantErr bool
	}{
		{
			name:    "create fails with remote client error",
			agent:   testkits.NewSharedPoolAgentBuilder().Build(),
			opts:    testkits.TaskOptions{ClientError: true},
			wantErr: true,
		},
		{
			name:    "create succeeds with no matching templates",
			agent:   testkits.NewSharedPoolAgentBuilder().Build(),
			opts:    testkits.TaskOptions{Client: testkits.BuildClient()},
			wantErr: false,
		},
		{
			name:  "create succeeds with sharedpool/jobs templates",
			agent: testkits.NewSharedPoolAgentBuilder().Build(),
			opts: testkits.TaskOptions{
				Client:    testkits.BuildClient(),
				Templates: config.Templates{"sharedpool/jobs/tikv-multitenant.yaml": tmpl},
			},
			wantErr: false,
		},
		{
			name:  "create skips non-sharedpool/jobs templates",
			agent: testkits.NewSharedPoolAgentBuilder().Build(),
			opts: testkits.TaskOptions{
				Client:    testkits.BuildClient(),
				Templates: config.Templates{"sharedpool/other.yaml": tmpl},
			},
			wantErr: false,
		},
	}

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

func TestServerlessVMPodScrapeTask_PostCreate(t *testing.T) {
	tests := []struct {
		name             string
		agent            *agentv2.SharedPoolAgent
		opts             testkits.TaskOptions
		vmpodscrapeNames []string
		wantErr          bool
	}{
		{
			name:    "post create fails with remote client error",
			agent:   testkits.NewSharedPoolAgentBuilder().Build(),
			opts:    testkits.TaskOptions{ClientError: true},
			wantErr: true,
		},
		{
			name:             "post create succeeds with no vmpodscrape names",
			agent:            testkits.NewSharedPoolAgentBuilder().Build(),
			opts:             testkits.TaskOptions{Client: testkits.BuildClient()},
			vmpodscrapeNames: nil,
			wantErr:          false,
		},
		{
			name:  "post create succeeds when vmpodscrape is ready",
			agent: testkits.NewSharedPoolAgentBuilder().Build(),
			opts: testkits.TaskOptions{
				Client: testkits.BuildClient(
					&vmoperatorv1beta1.VMPodScrape{
						ObjectMeta: metav1.ObjectMeta{
							Name:      "test-multitenant",
							Namespace: consts.ServerlessObservabilityNamespace,
						},
						Status: vmoperatorv1beta1.ScrapeObjectStatus{
							StatusMetadata: vmoperatorv1beta1.StatusMetadata{
								UpdateStatus: vmoperatorv1beta1.UpdateStatusOperational,
							},
						},
					},
				),
			},
			vmpodscrapeNames: []string{"test-multitenant"},
			wantErr:          false,
		},
		{
			name:  "post create fails when vmpodscrape not found",
			agent: testkits.NewSharedPoolAgentBuilder().Build(),
			opts: testkits.TaskOptions{
				Client: testkits.BuildClient(),
			},
			vmpodscrapeNames: []string{"missing-multitenant"},
			wantErr:          true,
		},
	}

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

func TestServerlessVMPodScrapeTask_Delete(t *testing.T) {
	tests := []struct {
		name    string
		agent   *agentv2.SharedPoolAgent
		opts    testkits.TaskOptions
		wantErr bool
	}{
		{
			name:    "delete fails with remote client error",
			agent:   testkits.NewSharedPoolAgentBuilder().Build(),
			opts:    testkits.TaskOptions{ClientError: true},
			wantErr: true,
		},
		{
			name:    "delete succeeds with no vmpodscrapes",
			agent:   testkits.NewSharedPoolAgentBuilder().Build(),
			opts:    testkits.TaskOptions{Client: testkits.BuildClient()},
			wantErr: false,
		},
		{
			name:  "delete succeeds with existing vmpodscrapes",
			agent: testkits.NewSharedPoolAgentBuilder().Build(),
			opts: testkits.TaskOptions{
				Client: testkits.BuildClient(
					&vmoperatorv1beta1.VMPodScrape{
						ObjectMeta: metav1.ObjectMeta{
							Name:      "test-multitenant",
							Namespace: consts.ServerlessObservabilityNamespace,
							Labels: map[string]string{
								consts.LabelKeyVMPodScrapeAgent: consts.AgentSharedPool,
							},
						},
					},
				),
			},
			wantErr: false,
		},
		{
			name:  "delete skips vmpodscrapes with wrong agent label",
			agent: testkits.NewSharedPoolAgentBuilder().Build(),
			opts: testkits.TaskOptions{
				Client: testkits.BuildClient(
					&vmoperatorv1beta1.VMPodScrape{
						ObjectMeta: metav1.ObjectMeta{
							Name:      "test-pd",
							Namespace: consts.ServerlessObservabilityNamespace,
							Labels: map[string]string{
								consts.LabelKeyVMPodScrapeAgent: consts.AgentKubernetes,
							},
						},
					},
				),
			},
			wantErr: false,
		},
	}

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

func TestServerlessVMPodScrapeTask_PostDelete(t *testing.T) {
	tests := []struct {
		name    string
		agent   *agentv2.SharedPoolAgent
		opts    testkits.TaskOptions
		wantErr bool
	}{
		{
			name:    "post delete fails with remote client error",
			agent:   testkits.NewSharedPoolAgentBuilder().Build(),
			opts:    testkits.TaskOptions{ClientError: true},
			wantErr: true,
		},
		{
			name:    "post delete succeeds when no vmpodscrapes remain",
			agent:   testkits.NewSharedPoolAgentBuilder().Build(),
			opts:    testkits.TaskOptions{Client: testkits.BuildClient()},
			wantErr: false,
		},
		{
			name:  "post delete fails when vmpodscrapes still exist",
			agent: testkits.NewSharedPoolAgentBuilder().Build(),
			opts: testkits.TaskOptions{
				Client: testkits.BuildClient(
					&vmoperatorv1beta1.VMPodScrape{
						ObjectMeta: metav1.ObjectMeta{
							Name:      "test-multitenant",
							Namespace: consts.ServerlessObservabilityNamespace,
							Labels: map[string]string{
								consts.LabelKeyVMPodScrapeAgent: consts.AgentSharedPool,
							},
						},
					},
				),
			},
			wantErr: true,
		},
		{
			name:  "post delete succeeds when only other agent vmpodscrapes remain",
			agent: testkits.NewSharedPoolAgentBuilder().Build(),
			opts: testkits.TaskOptions{
				Client: testkits.BuildClient(
					&vmoperatorv1beta1.VMPodScrape{
						ObjectMeta: metav1.ObjectMeta{
							Name:      "test-pd",
							Namespace: consts.ServerlessObservabilityNamespace,
							Labels: map[string]string{
								consts.LabelKeyVMPodScrapeAgent: consts.AgentKubernetes,
							},
						},
					},
				),
			},
			wantErr: false,
		},
	}

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

func TestServerlessVMPodScrapeTask_create(t *testing.T) {
	tmpl, err := template.New("test").Parse(`
metadata:
  name: test-multitenant
  namespace: {{.Namespace}}
spec:
  selector: {}
`)
	assert.NoError(t, err)

	tests := []struct {
		name                    string
		agent                   *agentv2.SharedPoolAgent
		opts                    testkits.TaskOptions
		wantErr                 bool
		wantVMPodScrapeNamesLen int
	}{
		{
			name:                    "create collects no names with no matching templates",
			agent:                   testkits.NewSharedPoolAgentBuilder().Build(),
			opts:                    testkits.TaskOptions{Client: testkits.BuildClient()},
			wantErr:                 false,
			wantVMPodScrapeNamesLen: 0,
		},
		{
			name:  "create collects names from sharedpool/jobs templates",
			agent: testkits.NewSharedPoolAgentBuilder().Build(),
			opts: testkits.TaskOptions{
				Client:    testkits.BuildClient(),
				Templates: config.Templates{"sharedpool/jobs/tikv-multitenant.yaml": tmpl},
			},
			wantErr:                 false,
			wantVMPodScrapeNamesLen: 1,
		},
		{
			name:  "create skips non-sharedpool/jobs templates",
			agent: testkits.NewSharedPoolAgentBuilder().Build(),
			opts: testkits.TaskOptions{
				Client:    testkits.BuildClient(),
				Templates: config.Templates{"sharedpool/other.yaml": tmpl},
			},
			wantErr:                 false,
			wantVMPodScrapeNamesLen: 0,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			cli := testkits.NewClientGetter(tt.opts.Client)
			task := makeServerlessVMPodScrapeTask(tt.agent, tt.opts)
			err := task.create(context.Background(), cli)
			if tt.wantErr {
				assert.Error(t, err)
				return
			}
			assert.NoError(t, err)
			assert.Len(t, task.vmpodscrapeNames, tt.wantVMPodScrapeNamesLen)
		})
	}
}
