package ngoperation

import (
	opent "github.com/tidbcloud/devops/entity/operation"
	"github.com/tidbcloud/devops/pkg/infra/clients/mgmthttpcli"
	evbus "github.com/tidbcloud/eventbus-datastruct/event"
	commonv1 "github.com/tidbcloud/tidb-management-service/api/spec/global/common/v1"
	nextgenv1 "github.com/tidbcloud/tidb-management-service/api/spec/global/nextgen/v1"

	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
)

var _ = Describe("[Resource Pool Event]", func() {
	It("uses platform tenant attribution for shared pools", func() {
		rp := &nextgenv1.ResourcePoolProfile{
			ResourcePool: &nextgenv1.ResourcePool{
				Id:        123,
				Name:      "shared-rp",
				OwnerType: nextgenv1.ResourcePool_SHARED,
				OwnerId:   456,
			},
			Region: &commonv1.Region{
				LogicalName:     "aws-us-west-2",
				CloudProviderId: commonv1.CloudProvider_AWS,
			},
		}
		sp := &mgmthttpcli.SharedPool{}

		ev, err := assembleResourcePoolEvent("ScaleResourcePool", evbus.EventStatusStarted, "ops@pingcap.com", rp, sp, "pool %s", "123")
		Expect(err).ToNot(HaveOccurred())
		Expect(ev.TenantID).To(Equal(uint64(0)))
	})

	It("keeps owner tenant attribution for organization-owned pools", func() {
		rp := &nextgenv1.ResourcePoolProfile{
			ResourcePool: &nextgenv1.ResourcePool{
				Id:        123,
				OwnerType: nextgenv1.ResourcePool_ORGANIZATION,
				OwnerId:   456,
			},
			Region: &commonv1.Region{
				LogicalName:     "aws-us-west-2",
				CloudProviderId: commonv1.CloudProvider_AWS,
			},
		}
		sp := &mgmthttpcli.SharedPool{}

		ev, err := assembleResourcePoolEvent("ScaleResourcePool", evbus.EventStatusStarted, "ops@pingcap.com", rp, sp, "pool %s", "123")
		Expect(err).ToNot(HaveOccurred())
		Expect(ev.TenantID).To(Equal(uint64(456)))
	})

	It("fails closed when resource pool owner type is unsupported", func() {
		rp := &nextgenv1.ResourcePoolProfile{
			ResourcePool: &nextgenv1.ResourcePool{
				Id:        123,
				OwnerType: nextgenv1.ResourcePool_OwnerType(-1),
			},
		}

		ev, err := assembleResourcePoolEvent("ScaleResourcePool", evbus.EventStatusStarted, "ops@pingcap.com", rp, &mgmthttpcli.SharedPool{}, "pool %s", "123")
		Expect(err).To(HaveOccurred())
		Expect(ev).To(BeNil())
	})

	It("falls back to injected tenant params when resource pool attribution is unavailable", func() {
		tenantID, ok := resourcePoolDisplayEventTenantIDFromParams(&opent.Instance{
			Params: map[opent.ParamName]string{
				opent.ParamTenantID: "456",
			},
		})

		Expect(ok).To(BeTrue())
		Expect(tenantID).To(Equal(uint64(456)))
	})
})
