package adapters

import (
	"context"
	"errors"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils"
	"gorm.io/gorm"
	"time"

	"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 CreateClusterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *CreateClusterLogic) CreateCluster(req *types.ClusterCreateReq) (resp *types.ClusterResp, err error) {
	adapter := &types.AdapterInfo{}
	result := l.svcCtx.DbEngin.Table("t_adapter").First(&adapter, req.AdapterId)
	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		return nil, errors.New("adapter does not exist")
	}
	cluster := types.ClusterInfo{}
	utils.Convert(req, &cluster)
	cluster.Id = utils.GenSnowflakeIDStr()
	cluster.CreateTime = time.Now().Format("2006-01-02 15:04:05")
	cluster.OwnerId = "0"
	tx := l.svcCtx.DbEngin.Table("t_cluster").Create(&cluster)
	if tx.Error != nil {
		logx.Errorf(tx.Error.Error())
		return nil, errors.New("cluster create failed")
	}
	return
}
