package cloud

import (
	"context"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils"
	"gitlink.org.cn/JointCloud/pcm-kubernetes/kubernetes"

	"gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

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

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

// NoticeTenant 通知更新租户数据
func (l *NoticeTenantLogic) NoticeTenant() (resp *types.CloudResp, err error) {
	var tenants []*models.ScTenantInfo
	//从p端kubernetes获取租户信息
	namespace, err := l.svcCtx.K8sRpc.ListNamespace(context.Background(), &kubernetes.NamespaceListReq{})
	if err != nil {
		logx.Errorf("获取租户信息失败:%v", err)
		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,
		})
	}
	tx := l.svcCtx.DbEngin.Save(&tenants)
	if tx.Error != nil {
		logx.Errorf("保存租户信息失败:%v", tx.Error)
		return nil, err
	}
	logx.Info("更新租户数据成功")
	return
}
