package central

import (
	"fmt"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
	centralapi "github.com/tidbcloud/core-svc/idl/pbgen/proto/central"

	openapiserverlessv1beta1 "github.com/tidbcloud/tidb-management-service/api/spec/tidb_cloud_open_api/serverless/v1beta1"
	"github.com/tidbcloud/tidb-management-service/tempo-wrapper/internal/api/types"
	apiutils "github.com/tidbcloud/tidb-management-service/tempo-wrapper/internal/api/utils"
	"github.com/tidbcloud/tidb-management-service/tempo-wrapper/pkg/grpc"
	coregrpc "github.com/tidbcloud/tidb-management-service/tempo-wrapper/pkg/grpc/core_portal"
	mgmtgrpc "github.com/tidbcloud/tidb-management-service/tempo-wrapper/pkg/grpc/mgmt"
	"github.com/tidbcloud/tidb-management-service/utilities/bizerr"
)

func GetPrivateLinkService(ctx *gin.Context) {
	req := &centralapi.GetPrivateLinkServiceReq{}
	// check org/project id
	orgId, err := strconv.ParseUint(ctx.Param("org_id"), 10, 64)
	if err != nil {
		types.BadRequestResp(ctx, fmt.Errorf("invalid org id: %w", err))
		return
	}
	projectId, err := strconv.ParseUint(ctx.Param("project_id"), 10, 64)
	if err != nil {
		types.BadRequestResp(ctx, fmt.Errorf("invalid project id: %w", err))
		return
	}

	clusterId, err := strconv.ParseUint(ctx.Param("cluster_id"), 10, 64)
	if err != nil {
		types.BadRequestResp(ctx, fmt.Errorf("invalid cluster id: %w", err))
		return
	}

	// set cluster org and project id
	req.OrgId = orgId
	req.ProjectId = projectId
	req.ClusterId = clusterId

	if ok, err := apiutils.IsNewServerlessCluster(ctx, clusterId, projectId, orgId); err != nil {
		types.InternalErrorResp(ctx, fmt.Errorf("check cluster failed: %w", err))
		return
	} else if ok {
		cluster, err := mgmtgrpc.GetServerlessCluster(grpc.NewContext(ctx), &openapiserverlessv1beta1.GetClusterRequest{
			ClusterId: strconv.FormatUint(clusterId, 10),
			View:      openapiserverlessv1beta1.ClusterView_BASIC,
		})
		if err != nil {
			types.GrpcErrorResp(ctx, err)
			return
		}
		types.SuccessResp(ctx, convertPrivateLinkService(cluster))
		return
	}

	// TDDO: use new open api
	// if ok, err := apiutils.IsNewDedicatedCluster(ctx, clusterId, projectId, orgId); err != nil {
	// 	types.InternalErrorResp(ctx, fmt.Errorf("check cluster failed: %w", err))
	// 	return
	// } else if ok {
	// 	types.SuccessResp(ctx, &emptypb.Empty{})
	// 	return
	// }

	// core-portal will split traffic to dedicated global
	// https://github.com/tidbcloud/core-svc/pull/1316
	resp, err := coregrpc.GetPrivateLinkService(grpc.NewContext(ctx), req)
	if err != nil {
		types.GrpcErrorResp(ctx, err)
		return
	}
	types.SuccessResp(ctx, resp)
}

func convertPrivateLinkService(c *openapiserverlessv1beta1.Cluster) *centralapi.GetPrivateLinkServiceResp {
	if c.Endpoints == nil || c.Endpoints.Private == nil || c.Endpoints.Private.Host == "" {
		return &centralapi.GetPrivateLinkServiceResp{
			PrivatelinkService: &centralapi.PrivateLinkService{
				CloudProvider: strings.ToLower(c.Region.CloudProvider.String()),
				Status:        centralapi.PrivateLinkService_NOT_CONFIGURE,
			},
			BaseResp: &centralapi.BaseResp{
				ErrCode: int64(bizerr.ErrCodeOK),
				ErrMsg:  "",
			},
		}
	}

	linkService := &centralapi.PrivateLinkService{
		Status:  centralapi.PrivateLinkService_ACTIVE,
		DnsName: c.Endpoints.Private.Host,
		Port:    c.Endpoints.Private.Port,
	}
	switch provider := c.Endpoints.Private.Provider.(type) {
	case *openapiserverlessv1beta1.Cluster_Endpoints_Private_Aws:
		linkService.CloudProvider = apiutils.AwsProvider
		linkService.Name = provider.Aws.ServiceName
		linkService.AzIds = provider.Aws.AvailabilityZone
	case *openapiserverlessv1beta1.Cluster_Endpoints_Private_Gcp:
		linkService.CloudProvider = apiutils.GcpProvider
		linkService.Name = provider.Gcp.ServiceAttachmentName
	}

	return &centralapi.GetPrivateLinkServiceResp{
		PrivatelinkService: linkService,
		BaseResp: &centralapi.BaseResp{
			ErrCode: int64(bizerr.ErrCodeOK),
			ErrMsg:  "",
		},
	}
}
