package central

import (
	"errors"
	"fmt"
	"strconv"

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

	globaldedicatedv1 "github.com/tidbcloud/tidb-management-service/api/spec/global/dedicated/v1"
	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"
	dedicatedgrpc "github.com/tidbcloud/tidb-management-service/tempo-wrapper/pkg/grpc/dedicated"
	mgmtgrpc "github.com/tidbcloud/tidb-management-service/tempo-wrapper/pkg/grpc/mgmt"
	"github.com/tidbcloud/tidb-management-service/utilities/bizerr"
)

func ChangePassword(ctx *gin.Context) {
	req := &centralapi.ChangePasswordReq{}
	err := types.ShouldBindJSON(ctx, req)
	if err != nil {
		types.BadRequestResp(ctx, fmt.Errorf("bind request body failed: %w", err))
		return
	}

	if req.Password == "" {
		types.BadRequestResp(ctx, errors.New("new password is empty"))
		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
		_, err := mgmtgrpc.ChangeServerlessRootPassword(grpc.NewContext(ctx), &openapiserverlessv1beta1.ChangeRootPasswordRequest{
			ClusterId: strconv.FormatUint(clusterId, 10),
			Password:  req.Password,
		})
		if err != nil {
			types.GrpcErrorResp(ctx, err)
			return
		}
		types.SuccessResp(ctx, &centralapi.DefaultResp{
			BaseResp: &centralapi.BaseResp{
				ErrCode: int64(bizerr.ErrCodeOK),
				ErrMsg:  "",
			},
		})
		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.SetDedicatedRootPassword(grpc.NewContext(ctx), &openapidedicatedv1beta1.ResetRootPasswordRequest{
			ClusterId:    strconv.FormatUint(clusterId, 10),
			RootPassword: req.Password,
		})
		if err != nil {
			types.GrpcErrorResp(ctx, err)
			return
		}
		types.SuccessResp(ctx, &centralapi.DefaultResp{
			BaseResp: &centralapi.BaseResp{
				ErrCode: int64(bizerr.ErrCodeOK),
				ErrMsg:  "",
			},
		})
		return
	}

	_, err = dedicatedgrpc.ChangeClusterPassword(grpc.NewContext(ctx), &globaldedicatedv1.ChangeClusterPasswdRequest{
		ClusterId: clusterId,
		Passwd:    req.Password,
	})
	if err != nil {
		types.GrpcErrorResp(ctx, err)
		return
	}
	types.SuccessResp(ctx, &centralapi.DefaultResp{BaseResp: successBaseResp()})
}
