package server

import (
	"context"

	"github.com/tidbcloud/cluster-service-ng/domain/entity"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

func (s *serverImpl) GetProviderRole(ctx context.Context, tidbCusterId string) (*entity.ProviderRole, error) {

	if tidbCusterId == "" {
		return nil, status.Errorf(codes.InvalidArgument, "tidbCluster id is required")
	}

	tidbCluster, err := s.tidbClusterRepo.Load(ctx, tidbCusterId, false)
	if err != nil {
		if status.Code(err) != codes.NotFound {
			return nil, status.Errorf(codes.Internal, "failed to load tidbCluster: %s", err)
		}

		// not found, check if it's in creating
		return nil, status.Errorf(codes.NotFound, "tidbCluster %s not found", tidbCusterId)
	}

	sharedPool, err := s.sharedPoolRepo.Load(ctx, tidbCluster.GetSharedPoolId(), false)
	if err != nil {
		if status.Code(err) != codes.NotFound {
			return nil, status.Errorf(codes.Internal, "failed to load sharedPool: %s", err)
		}
		// not found, check if it's in creating
		return nil, status.Errorf(codes.NotFound, "sharedPool %s not found", tidbCluster.GetSharedPoolId())
	}

	return &entity.ProviderRole{
		CloudIamIdentity: sharedPool.GetProvider().GetIdentityId(),
		NodeRole:         sharedPool.GetProvider().GetNodeRole(),
		ExternalId:       tidbCluster.GetId(),
	}, nil
}
