package v1beta

import (
	"fmt"
	"strconv"

	"github.com/gin-gonic/gin"
	openapilegacy "github.com/tidbcloud/idl/pbgen/proto/openapi/cm"
	"google.golang.org/protobuf/types/known/emptypb"

	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/internal/auth"
	"github.com/tidbcloud/tidb-management-service/tempo-wrapper/pkg/grpc"
	mgmtgrpc "github.com/tidbcloud/tidb-management-service/tempo-wrapper/pkg/grpc/mgmt"
	openapigrpc "github.com/tidbcloud/tidb-management-service/tempo-wrapper/pkg/grpc/openapi"
)

func DeleteCluster(ctx *gin.Context) {
	req := &openapilegacy.DeleteClusterReq{}

	orgId, err := auth.GetOrgIDByHeader(ctx)
	if err != nil {
		types.OpenAPIInvalidArgumentResp(ctx, err)
		return
	}

	projectId, err := strconv.ParseUint(ctx.Param("project_id"), 10, 64)
	if err != nil {
		types.OpenAPIInvalidArgumentResp(ctx, fmt.Errorf("invalid project id: %w", err))
		return
	}

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

	req.ProjectId = projectId
	req.ClusterId = clusterId

	// serverless
	if ok, err := apiutils.IsNewServerlessCluster(ctx, clusterId, projectId, orgId); err != nil {
		types.OpenAPIInternalErrorResp(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.OpenAPIErrorResp(ctx, err)
			return
		}
		types.SuccessResp(ctx, &emptypb.Empty{})
		return
	}

	// dedicated
	if ok, err := apiutils.IsNewDedicatedCluster(ctx, clusterId, projectId, orgId); err != nil {
		types.OpenAPIInternalErrorResp(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.OpenAPIErrorResp(ctx, err)
			return
		}
		types.SuccessResp(ctx, &emptypb.Empty{})
		return
	}

	// OpenAPI
	resp, err := openapigrpc.DeleteCluster(grpc.NewContext(ctx), req)
	if err != nil {
		types.OpenAPIErrorResp(ctx, err)
		return
	}

	types.SuccessResp(ctx, resp)
}
