package inner

import (
	"errors"
	"fmt"
	"strconv"

	"github.com/gin-gonic/gin"

	tidbmgmtservicev1 "github.com/tidbcloud/tidb-management-service/api/spec/tidb_mgmt_service/v1"
	"github.com/tidbcloud/tidb-management-service/tempo-wrapper/internal/api/types"
	"github.com/tidbcloud/tidb-management-service/tempo-wrapper/pkg/grpc"
	mgmtgrpc "github.com/tidbcloud/tidb-management-service/tempo-wrapper/pkg/grpc/mgmt"
)

func ShowComponentNodeInfo(ctx *gin.Context) {
	req := &tidbmgmtservicev1.ShowComponentNodeInfoRequest{}
	if err := types.ShouldBindJSON(ctx, req); err != nil {
		types.BadRequestResp(ctx, fmt.Errorf("bind request body failed: %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
	}
	req.ClusterId = clusterId
	req.ProjectId, err = strconv.ParseUint(ctx.Query("project_id"), 10, 64)
	if err != nil {
		types.BadRequestResp(ctx, fmt.Errorf("invalid project id: %w", err))
		return
	}
	req.OrganizationId, err = strconv.ParseUint(ctx.Query("organization_id"), 10, 64)
	if err != nil {
		types.BadRequestResp(ctx, fmt.Errorf("invalid organization id: %w", err))
		return
	}
	if req.ClusterId == 0 || req.OrganizationId == 0 || req.ProjectId == 0 {
		types.BadRequestResp(ctx, errors.New("cluster id, organization id and project id are required"))
		return
	}

	resp, err := mgmtgrpc.ShowDedicatedComponentNodeInfo(grpc.NewContext(ctx), req)
	if err != nil {
		types.GrpcErrorResp(ctx, err)
		return
	}
	types.SuccessRespNotProtoNames(ctx, resp)
}
