package cloud

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/types"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils"
	"gitlink.org.cn/JointCloud/pcm-kubernetes/kubernetes"
)

type UpdateTenantLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateTenantLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateTenantLogic {
	return &UpdateTenantLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// UpdateTenant 更新租户数据
func (l *UpdateTenantLogic) UpdateTenant(req *types.UpdateTenantReq) (resp *types.CloudResp, err error) {
	var tenants []*models.ScTenantInfo
	//从p端kubernetes获取租户信息
	namespace, err := l.svcCtx.K8sRpc.ListNamespace(context.Background(), &kubernetes.NamespaceListReq{})
	if err != nil {
		return nil, err
	}
	//先删除所有租户数据
	l.svcCtx.DbEngin.Where("type = 0").Delete(models.ScTenantInfo{})

	//遍历租户信息
	for k, v := range namespace.Data {
		tenants = append(tenants, &models.ScTenantInfo{
			Id:         utils.GenSnowflakeID(),
			TenantName: k,
			Clusters:   v,
			Type:       0,
		})
	}
	l.svcCtx.DbEngin.Save(&tenants)
	return
}
