package cluster

import (
	"context"

	"github.com/tidbcloud/dataflow-service/internal/bizutils"
	"github.com/tidbcloud/dataflow-service/internal/common"
	"github.com/tidbcloud/dataflow-service/internal/db/entity"
	"github.com/tidbcloud/dataflow-service/internal/grpc/grpcli"
	"github.com/tidbcloud/dataflow-service/internal/utils"
	"github.com/tidbcloud/pkgv2/log"
	"go.uber.org/zap"
	"google.golang.org/genproto/googleapis/rpc/errdetails"
)

type DataIngestionProfile struct {
	Type          string
	AwsExternalId string
	AwsAccountId  string
	GcpAccountId  string
}

func (c UserContext) GetDataIngestionProfile(ctx context.Context, clusterID entity.ID) (*DataIngestionProfile, error) {
	logger := log.WithContextS(ctx)
	cluster, bizErr := grpcli.GetClusterWithDataplaneByID(ctx, clusterID.Uint64())
	if bizErr != nil {
		errMsg := "Failed to get cluster information. Please check whether the cluster is cleared or deleted."
		logger.Warn(errMsg, zap.Error(bizErr))
		if bizErr := bizutils.AppendErrorDetails(ctx, &errdetails.ErrorInfo{
			Reason: bizErr.Error(),
		}); bizErr != nil {
			logger.Warn("append error detail error", zap.Error(bizErr))
		}
		return nil, utils.WrapAsErrorCodeErr(bizErr, errMsg)
	}

	ctx = common.ContextWithImport(ctx)
	network, err := common.GetNetworkByCluster(ctx, cluster)
	if err != nil {
		return nil, err
	}
	return &DataIngestionProfile{
		Type:          cluster.InfraProviderType,
		AwsExternalId: network.AWSExternalID(),
		AwsAccountId:  network.AWSAccountID(),
		GcpAccountId:  network.GCPServiceAccountEmail(),
	}, nil
}
