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"
	"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 ResumeCluster(ctx *gin.Context) {
	req := &centralapi.ClusterIdReq{}
	err := types.ShouldBindJSON(ctx, req)
	if err != nil {
		types.BadRequestResp(ctx, fmt.Errorf("bind request body failed: %w", err))
		return
	}

	// check org/project id
	orgId, err := strconv.ParseUint(ctx.Param("org_id"), 10, 64)
	if err != nil {
		types.UnauthorizedResp(ctx, err)
		return
	}
	projectId, err := strconv.ParseUint(ctx.Param("project_id"), 10, 64)
	if err != nil {
		types.UnauthorizedResp(ctx, 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 org and project id
	req.OrgId = orgId
	req.ProjectId = projectId
	req.ClusterId = clusterId

	// check is new serverless cluster
	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 {
		// is serverless cluster
		types.SuccessResp(ctx, &centralapi.DefaultResp{
			BaseResp: &centralapi.BaseResp{
				ErrCode: int64(bizerr.ErrCodePermission),
				ErrMsg:  "serverless cluster does not support resume",
			},
		})
		return
	}

	// check is new dedicated cluster
	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 { // is new dedicated cluster
		_, err := mgmtgrpc.ResumeDedicatedCluster(grpc.NewContext(ctx), &openapidedicatedv1beta1.ResumeClusterRequest{
			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
	}

	// core-portal
	resp, err := coregrpc.Resume(grpc.NewContext(ctx), req)
	if err != nil {
		types.GrpcErrorResp(ctx, err)
		return
	}
	types.SuccessResp(ctx, resp)
}
