package central

import (
	"fmt"
	"strconv"

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

	openapidedicatedv1beta1 "github.com/tidbcloud/tidb-management-service/api/spec/tidb_cloud_open_api/dedicated/v1beta1"
	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 DeleteCluster(ctx *gin.Context) {
	req := &centralapi.ClusterIdReq{}
	// 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: %s,: %w", ctx.Param("cluster_id"), err))
		return
	}

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

	// serverless
	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 {
		_, err := mgmtgrpc.DeleteServerlessCluster(grpc.NewContext(ctx),
			&openapiserverlessv1beta1.DeleteClusterRequest{ClusterId: strconv.FormatUint(clusterId, 10)})
		if err != nil {
			types.GrpcErrorResp(ctx, err)
			return
		}
		types.SuccessResp(ctx, &centralapi.DefaultResp{
			BaseResp: &centralapi.BaseResp{
				ErrCode: int64(bizerr.ErrCodeOK),
				ErrMsg:  "",
			},
		})
		return
	}

	// dedicated
	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 {
		_, err := mgmtgrpc.DeleteDedicatedCluster(grpc.NewContext(ctx),
			&openapidedicatedv1beta1.DeleteClusterRequest{ClusterId: strconv.FormatUint(clusterId, 10)})
		if err != nil {
			types.GrpcErrorResp(ctx, err)
			return
		}
		types.SuccessResp(ctx, &centralapi.DefaultResp{
			BaseResp: &centralapi.BaseResp{
				ErrCode: int64(bizerr.ErrCodeOK),
				ErrMsg:  "",
			},
		})
		return
	}

	resp, err := coregrpc.DeleteCluster(grpc.NewContext(ctx), req)
	if err != nil {
		types.GrpcErrorResp(ctx, err)
		return
	}
	types.SuccessResp(ctx, resp)
}
