package database

import (
	"github.com/zeromicro/go-zero/core/logx"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/entity"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"
	"gorm.io/gorm"
)

type CloudStorage struct {
	DbEngin *gorm.DB
}

func NewCloudStorage(dbEngin *gorm.DB) *CloudStorage {
	return &CloudStorage{DbEngin: dbEngin}
}

func (c *CloudStorage) GetProviderParams() ([]entity.ProviderParams, error) {
	var proParams []entity.ProviderParams
	sqlstr := "SELECT SUM(a.disk_avail) as disk_avail,SUM(a.mem_avail) as mem_avail,SUM(a.cpu_total * a.cpu_usable) as cpu_avail,participant_id from (SELECT * from sc_node_avail_info where created_time in (SELECT MAX(created_time) as time  from sc_node_avail_info where deleted_flag = 0 GROUP BY participant_id,node_name)) a GROUP BY a.participant_id"
	c.DbEngin.Raw(sqlstr).Scan(&proParams)
	if len(proParams) == 0 {
		return nil, nil
	}
	return proParams, nil
}

func (c *CloudStorage) FindAvailableParticipants() ([]entity.Participant, error) {
	var parts []entity.Participant
	sqlstr := "select id as participant_id, name as name from sc_participant_phy_info"
	c.DbEngin.Raw(sqlstr).Scan(&parts)
	if len(parts) == 0 {
		return nil, nil
	}
	return parts, nil
}
func (c *CloudStorage) GetClustersByAdapterId(id string) (*types.ClusterListResp, error) {
	var resp types.ClusterListResp
	tx := c.DbEngin.Raw("select * from t_cluster where `deleted_at` IS NULL and `adapter_id` = ? ORDER BY create_time Desc", id).Scan(&resp.List)
	if tx.Error != nil {
		logx.Errorf(tx.Error.Error())
		return nil, tx.Error
	}
	return &resp, nil
}
