package tenantaction

import (
	"context"
	"testing"

	commonv1 "github.com/tidbcloud/tidb-management-service/api/spec/global/common/v1"
	nextgenv1 "github.com/tidbcloud/tidb-management-service/api/spec/global/nextgen/v1"
	mgmtv1 "github.com/tidbcloud/tidb-management-service/api/spec/tidb_mgmt_service/v1"
	"google.golang.org/grpc"

	opent "github.com/tidbcloud/devops/entity/operation"
	"github.com/tidbcloud/devops/pkg/infra/clients/coresvccli"
	"github.com/tidbcloud/devops/pkg/service/operation/actions"
)

type fakeRcuQuotaServiceClient struct {
	updatedPlan commonv1.ServicePlan
}

func (f *fakeRcuQuotaServiceClient) ListOrgRcuQuotas(ctx context.Context, in *nextgenv1.ListOrgRcuQuotasRequest, opts ...grpc.CallOption) (*nextgenv1.ListOrgRcuQuotasResponse, error) {
	return &nextgenv1.ListOrgRcuQuotasResponse{}, nil
}

func (f *fakeRcuQuotaServiceClient) UpdateRcuQuota(ctx context.Context, in *nextgenv1.UpdateRcuQuotaRequest, opts ...grpc.CallOption) (*nextgenv1.RcuQuota, error) {
	f.updatedPlan = in.GetRcuQuota().GetServicePlan()
	return in.GetRcuQuota(), nil
}

func Test_updateRcuQuota_Start_supportsNewServicePlan(t *testing.T) {
	rcuQuotaClient := &fakeRcuQuotaServiceClient{}
	a := &updateRcuQuota{comps: &actions.Components{CoreSvc: &coresvccli.CoreSvcCli{Mgmt: &coresvccli.MgmtService{RcuQuota: rcuQuotaClient}}}}

	result, err := a.Start(context.Background(), &opent.Instance{Params: map[opent.ParamName]string{
		opent.ParamTenantID:       "1",
		opent.ParamServicePlan:    commonv1.ServicePlan_Essential_V2.String(),
		opent.ParamInstanceMaxRCU: "5000",
	}})
	if err != nil {
		t.Fatalf("Start() error = %v", err)
	}
	if result.Result != opent.ActionStatusSucceeded {
		t.Fatalf("Start() result = %s, output = %s", result.Result, result.ActionOutput)
	}
	if rcuQuotaClient.updatedPlan != commonv1.ServicePlan_Essential_V2 {
		t.Fatalf("updated service plan = %s, want %s", rcuQuotaClient.updatedPlan.String(), commonv1.ServicePlan_Essential_V2.String())
	}
}

var _ mgmtv1.RcuQuotaServiceClient = (*fakeRcuQuotaServiceClient)(nil)
