package facade_imp

import (
	"context"
	"fmt"

	"github.com/tidbcloud/chaos-svc/pkg/domain/facade"
	"github.com/tidbcloud/chaos-svc/pkg/infra/config"
	"github.com/tidbcloud/core-svc/idl/pbgen/proto/core"
	"github.com/tidbcloud/pkgv2/bizerr"
	tigrpc "github.com/tidbcloud/tiinf/transport/tigrpc/client"
)

type coreSvcImp struct {
	cli core.CoreServiceClient
}

func NewCoreSvc(conf *config.ChaosConfig) facade.CoreSvc {
	conn, err := tigrpc.NewClientConn(conf.ServerConfig.SvcAddresses.CoreSvcAddr, tigrpc.WithDefault())
	if err != nil {
		panic(fmt.Sprintf("dial core-svc: %s", err))
	}

	return &coreSvcImp{cli: core.NewCoreServiceClient(conn)}
}

func (imp *coreSvcImp) GetCluster(ctx context.Context, clusterID uint64) (*facade.TiDBCluster, bizerr.BizError) {
	req := &core.ListClustersReq{
		Filter: &core.ClusterFilter{
			ClusterIds: []uint64{clusterID},
		},
		WithDataPlaneInfo: true,
	}
	resp, err := imp.cli.ListClusters(ctx, req)
	if err != nil {
		return nil, bizerr.WrapGrpcError(err, "GetCluster")
	}

	cluster := resp.Clusters[clusterID]
	if cluster == nil {
		return nil, bizerr.New(bizerr.ErrCodeRecordNotFound, "cluster not found")
	}
	return &facade.TiDBCluster{
		NetworkName: cluster.DataPlaneInfo.NetworkName,
		ProjectID:   cluster.ProjectId,
	}, nil
}
