/*
Copyright 2024.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package integrationtask

import (
	"testing"

	"github.com/go-logr/logr/testr"
	"github.com/stretchr/testify/assert"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	o11yv1 "github.com/tidbcloud/observability/api/regionalserver/resourceworker/v1"
	"github.com/tidbcloud/observability/pkg/common/constants"
	"github.com/tidbcloud/observability/pkg/common/structs"
	"github.com/tidbcloud/observability/pkg/resourceworker/controllers/integrationtask/v2/task"
)

func newTestContextForTaskBuilder(labels map[string]string) *task.Context {
	integrationTask := &o11yv1.IntegrationTask{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "test-task",
			Namespace: "default",
			Labels:    labels,
		},
		Spec: o11yv1.IntegrationTaskSpec{
			ClusterID: "cluster-1",
		},
	}

	return &task.Context{
		Task:   integrationTask,
		Logger: testr.New(&testing.T{}),
		Client: nil,
		ServiceInfo: structs.ServiceInfo{
			Vendor: "aws",
			Region: "us-west-2",
		},
	}
}

func TestGetIntegrationTasks_WithLabelInternal(t *testing.T) {
	labels := map[string]string{
		constants.LabelInternal: "true",
	}
	ctx := newTestContextForTaskBuilder(labels)

	tasks := GetIntegrationTasks(nil, ctx)

	assert.Equal(t, 5, len(tasks))

	assert.Equal(t, "Guardian", tasks[0].Name())

	assert.Equal(t, "ServiceAccount", tasks[1].Name())

	assert.Equal(t, "S3Bucket", tasks[2].Name())

	assert.Equal(t, "ConfigMap", tasks[3].Name())

	assert.Equal(t, "Deployment", tasks[4].Name())
}

func TestGetIntegrationTasks_WithoutLabelInternal(t *testing.T) {
	labels := map[string]string{}
	ctx := newTestContextForTaskBuilder(labels)

	tasks := GetIntegrationTasks(nil, ctx)

	assert.Equal(t, 5, len(tasks))

	assert.Equal(t, "Guardian", tasks[0].Name())

	assert.Equal(t, "S3Bucket", tasks[1].Name())

	assert.Equal(t, "IAMRole", tasks[2].Name())

	assert.Equal(t, "ConfigMap", tasks[3].Name())

	assert.Equal(t, "Deployment", tasks[4].Name())
}

func TestGetIntegrationTasks_TenantScopeUsesLegacyChain(t *testing.T) {
	integrationTask := &o11yv1.IntegrationTask{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "test-task",
			Namespace: "prod-devtier-tenant123",
			Labels: map[string]string{
				constants.LabelTenantID: "tenant123",
				constants.LabelBizType:  "prod-devtier",
			},
		},
		Spec: o11yv1.IntegrationTaskSpec{
			Scope:    o11yv1.ScopeTenant,
			TaskType: o11yv1.SqlStmtTask,
		},
	}
	ctx := &task.Context{
		Task:        integrationTask,
		Logger:      testr.New(t),
		ServiceInfo: structs.ServiceInfo{Region: "ap-southeast-5"},
	}

	tasks := GetIntegrationTasks(nil, ctx)

	assert.Equal(t, 5, len(tasks))
	assert.Equal(t, "Guardian", tasks[0].Name())
	assert.Equal(t, "S3Bucket", tasks[1].Name())
	assert.Equal(t, "IAMRole", tasks[2].Name())
	assert.Equal(t, "ConfigMap", tasks[3].Name())
	assert.Equal(t, "Deployment", tasks[4].Name())
}

func TestGetIntegrationTasks_WithLabelInternalFalse(t *testing.T) {
	labels := map[string]string{
		constants.LabelInternal: "false",
	}
	ctx := newTestContextForTaskBuilder(labels)

	tasks := GetIntegrationTasks(nil, ctx)

	assert.Equal(t, 5, len(tasks))

	assert.Equal(t, "Guardian", tasks[0].Name())
	assert.Equal(t, "S3Bucket", tasks[1].Name())
	assert.Equal(t, "IAMRole", tasks[2].Name())
	assert.Equal(t, "ConfigMap", tasks[3].Name())
	assert.Equal(t, "Deployment", tasks[4].Name())
}

func TestGetIntegrationTasks_WithLabelInternalEmpty(t *testing.T) {
	labels := map[string]string{
		constants.LabelInternal: "",
	}
	ctx := newTestContextForTaskBuilder(labels)

	tasks := GetIntegrationTasks(nil, ctx)

	assert.Equal(t, 5, len(tasks))

	assert.Equal(t, "Guardian", tasks[0].Name())
	assert.Equal(t, "S3Bucket", tasks[1].Name())
	assert.Equal(t, "IAMRole", tasks[2].Name())
	assert.Equal(t, "ConfigMap", tasks[3].Name())
	assert.Equal(t, "Deployment", tasks[4].Name())
}

func TestGetIntegrationTasks_TaskOrderIsCorrect(t *testing.T) {
	t.Run("internal task chain order", func(t *testing.T) {
		labels := map[string]string{
			constants.LabelInternal: "true",
		}
		ctx := newTestContextForTaskBuilder(labels)

		tasks := GetIntegrationTasks(nil, ctx)

		assert.Equal(t, "Guardian", tasks[0].Name())
		assert.Equal(t, "ServiceAccount", tasks[1].Name())
		assert.Equal(t, "S3Bucket", tasks[2].Name())
		assert.Equal(t, "ConfigMap", tasks[3].Name())
		assert.Equal(t, "Deployment", tasks[4].Name())
	})

	t.Run("external task chain order", func(t *testing.T) {
		labels := map[string]string{}
		ctx := newTestContextForTaskBuilder(labels)

		tasks := GetIntegrationTasks(nil, ctx)

		assert.Equal(t, "Guardian", tasks[0].Name())
		assert.Equal(t, "S3Bucket", tasks[1].Name())
		assert.Equal(t, "IAMRole", tasks[2].Name())
		assert.Equal(t, "ConfigMap", tasks[3].Name())
		assert.Equal(t, "Deployment", tasks[4].Name())
	})
}

func TestGetIntegrationTasks_BothChainsHaveSameLength(t *testing.T) {
	vectorCtx := newTestContextForTaskBuilder(map[string]string{
		constants.LabelInternal: "true",
	})
	legacyCtx := newTestContextForTaskBuilder(map[string]string{})

	vectorTasks := GetIntegrationTasks(nil, vectorCtx)
	legacyTasks := GetIntegrationTasks(nil, legacyCtx)

	assert.Equal(t, 5, len(vectorTasks))
	assert.Equal(t, 5, len(legacyTasks))
}

func TestGetIntegrationTasks_InternalUsesServiceAccount(t *testing.T) {
	internalCtx := newTestContextForTaskBuilder(map[string]string{
		constants.LabelInternal: "true",
	})
	externalCtx := newTestContextForTaskBuilder(map[string]string{})

	internalTasks := GetIntegrationTasks(nil, internalCtx)
	externalTasks := GetIntegrationTasks(nil, externalCtx)

	// Both chains share Guardian as first task
	assert.Equal(t, internalTasks[0].Name(), externalTasks[0].Name())
	assert.Equal(t, "Guardian", internalTasks[0].Name())

	// Internal tasks use ServiceAccount; external tasks use IAMRole after the shared S3Bucket step
	assert.Equal(t, "ServiceAccount", internalTasks[1].Name())
	assert.Equal(t, "S3Bucket", externalTasks[1].Name())
	assert.Equal(t, "IAMRole", externalTasks[2].Name())
}
