/*
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 task

import (
	"testing"

	"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"
)

func newIdentityContext(scope o11yv1.TaskScope, labels map[string]string, clusterID string, taskType o11yv1.TaskType) *Context {
	return &Context{
		Task: &o11yv1.IntegrationTask{
			ObjectMeta: metav1.ObjectMeta{
				Name:      "test-task",
				Namespace: "prod-devtier-tenant123",
				Labels:    labels,
			},
			Spec: o11yv1.IntegrationTaskSpec{
				Scope:         scope,
				ClusterID:     clusterID,
				TaskType:      taskType,
				AccessRoleARN: "acs:ram::123456789012:role/user",
			},
		},
		ServiceInfo: structs.ServiceInfo{Region: "ap-southeast-5"},
	}
}

func TestIdentity_ClusterScopeDefault(t *testing.T) {
	labels := map[string]string{
		constants.LabelTenantID: "tenant123",
		constants.LabelBizType:  "prod-devtier",
		constants.LabelAlias:    "o11y-ext-tenant123",
	}
	c := newIdentityContext("", labels, "cluster789", o11yv1.SlowQueryTask)

	id, err := c.Identity()
	assert.NoError(t, err)
	assert.False(t, id.IsTenant())
	assert.Equal(t, o11yv1.ScopeCluster, id.Scope)
	assert.Equal(t, "tenant123", id.TenantID)
	assert.Equal(t, "cluster789", id.ClusterID)
	assert.Equal(t, "ap-southeast-5", id.Region)
	// Cluster scope keeps the historical per-tenant suffix.
	assert.Equal(t, "tenant123", id.ResourceSuffix())
}

func TestIdentity_TenantScope(t *testing.T) {
	labels := map[string]string{
		constants.LabelTenantID: "tenant123",
		constants.LabelBizType:  "prod-devtier",
		constants.LabelAlias:    "o11y-ext-tenant123",
	}
	c := newIdentityContext(o11yv1.ScopeTenant, labels, "", o11yv1.SqlStmtTask)

	id, err := c.Identity()
	assert.NoError(t, err)
	assert.True(t, id.IsTenant())
	assert.Equal(t, "tenant123", id.TenantID)
	assert.Equal(t, "prod-devtier", id.BizType)
	assert.Equal(t, "ap-southeast-5", id.Region)
	assert.Empty(t, id.ClusterID)
	// Tenant scope isolates each (tenant, dataType) pipeline.
	assert.Equal(t, "tenant123-sqlstmt", id.ResourceSuffix())
}

func TestIdentity_BucketSharePolicy(t *testing.T) {
	labels := map[string]string{
		constants.LabelTenantID: "tenant123",
		constants.LabelBizType:  "prod-devtier",
	}
	c := newIdentityContext(o11yv1.ScopeTenant, labels, "", o11yv1.SqlStmtTask)
	c.Task.Spec.BucketSharePolicy = o11yv1.BucketSharePolicyExclusive

	id, err := c.Identity()
	assert.NoError(t, err)
	assert.Equal(t, o11yv1.BucketSharePolicyExclusive, id.BucketSharePolicy)
	assert.NoError(t, id.ValidateCreatable())
}

func TestIdentity_ValidateCreatable_RejectsInvalidBucketSharePolicy(t *testing.T) {
	labels := map[string]string{
		constants.LabelTenantID: "tenant123",
		constants.LabelBizType:  "prod-devtier",
	}
	c := newIdentityContext(o11yv1.ScopeTenant, labels, "", o11yv1.SqlStmtTask)
	c.Task.Spec.BucketSharePolicy = o11yv1.BucketSharePolicy("region-wide")

	id, err := c.Identity()
	assert.NoError(t, err)
	assert.Error(t, id.ValidateCreatable())
}

func TestIdentity_TenantScope_MissingTenantID(t *testing.T) {
	labels := map[string]string{
		constants.LabelBizType: "prod-devtier",
	}
	c := newIdentityContext(o11yv1.ScopeTenant, labels, "", o11yv1.SqlStmtTask)

	_, err := c.Identity()
	assert.Error(t, err)
}

func TestIdentity_TenantScope_MissingBizType(t *testing.T) {
	labels := map[string]string{
		constants.LabelTenantID: "tenant123",
	}
	c := newIdentityContext(o11yv1.ScopeTenant, labels, "", o11yv1.SqlStmtTask)

	_, err := c.Identity()
	assert.Error(t, err)
}

func TestIdentity_TenantScope_MissingTaskType(t *testing.T) {
	labels := map[string]string{
		constants.LabelTenantID: "tenant123",
		constants.LabelBizType:  "prod-devtier",
	}
	c := newIdentityContext(o11yv1.ScopeTenant, labels, "", "")

	_, err := c.Identity()
	assert.Error(t, err)
}

func TestIdentity_UnknownScope(t *testing.T) {
	labels := map[string]string{
		constants.LabelTenantID: "tenant123",
		constants.LabelBizType:  "prod-devtier",
	}
	c := newIdentityContext(o11yv1.TaskScope("bogus"), labels, "", o11yv1.SqlStmtTask)

	_, err := c.Identity()
	assert.Error(t, err)
}

func TestIdentity_ValidateCreatable_AllowsAllTiers(t *testing.T) {
	for _, bizType := range []string{
		"prod-devtier",
		"staging-tidbcloud",
		"tidbcloud",
		"staging-tidbcloud-nextgen",
		constants.DefaultByocBizType,
	} {
		labels := map[string]string{
			constants.LabelTenantID: "tenant123",
			constants.LabelBizType:  bizType,
		}
		c := newIdentityContext(o11yv1.ScopeTenant, labels, "", o11yv1.SlowQueryTask)

		id, err := c.Identity()
		assert.NoError(t, err)
		assert.NoError(t, id.ValidateCreatable(), "tenant-scoped %q must be accepted", bizType)
	}

	dedicatedCluster := newIdentityContext(o11yv1.ScopeCluster, map[string]string{
		constants.LabelTenantID: "tenant123",
		constants.LabelBizType:  "staging-tidbcloud",
	}, "cluster789", o11yv1.SlowQueryTask)
	cid, err := dedicatedCluster.Identity()
	assert.NoError(t, err)
	assert.NoError(t, cid.ValidateCreatable())
}
