package mq

import (
	"fmt"

	"gitlink.org.cn/cloudream/common/consts/errorcode"
	"gitlink.org.cn/cloudream/common/pkgs/logger"
	"gitlink.org.cn/cloudream/common/pkgs/mq"
	coormq "gitlink.org.cn/cloudream/jcs-pub/common/pkgs/mq/coordinator"
	cortypes "gitlink.org.cn/cloudream/jcs-pub/coordinator/types"
)

func (svc *Service) GetHubConfig(msg *coormq.GetHubConfig) (*coormq.GetHubConfigResp, *mq.CodeMessage) {
	log := logger.WithField("HubID", msg.HubID)

	hub, err := svc.db.Hub().GetByID(svc.db.DefCtx(), msg.HubID)
	if err != nil {
		log.Warnf("getting hub: %v", err)
		return nil, mq.Failed(errorcode.OperationFailed, fmt.Sprintf("getting hub: %v", err))
	}

	return mq.ReplyOK(coormq.RespGetHubConfig(hub))
}

func (svc *Service) GetHubs(msg *coormq.GetHubs) (*coormq.GetHubsResp, *mq.CodeMessage) {
	var hubs []*cortypes.Hub

	if msg.HubIDs == nil {
		get, err := svc.db.Hub().GetAllHubs(svc.db.DefCtx())
		if err != nil {
			logger.Warnf("getting all hubs: %s", err.Error())
			return nil, mq.Failed(errorcode.OperationFailed, "get all hub failed")
		}
		for _, hub := range get {
			h := hub
			hubs = append(hubs, &h)
		}

	} else {
		// 可以不用事务
		get, err := svc.db.Hub().BatchGetByID(svc.db.DefCtx(), msg.HubIDs)
		if err != nil {
			logger.Warnf("batch get hubs by id: %s", err.Error())
			return nil, mq.Failed(errorcode.OperationFailed, fmt.Sprintf("batch get hubs by id: %v", err))
		}

		getMp := make(map[cortypes.HubID]cortypes.Hub)
		for _, hub := range get {
			getMp[hub.HubID] = hub
		}

		for _, id := range msg.HubIDs {
			if hub, ok := getMp[id]; ok {
				h := hub
				hubs = append(hubs, &h)
			} else {
				hubs = append(hubs, nil)
			}
		}
	}

	return mq.ReplyOK(coormq.NewGetHubsResp(hubs))
}

func (svc *Service) GetHubConnectivities(msg *coormq.GetHubConnectivities) (*coormq.GetHubConnectivitiesResp, *mq.CodeMessage) {
	cons, err := svc.db.HubConnectivity().BatchGetByFromHub(svc.db.DefCtx(), msg.HubIDs)
	if err != nil {
		logger.Warnf("batch get hub connectivities by from hub: %s", err.Error())
		return nil, mq.Failed(errorcode.OperationFailed, "batch get hub connectivities by from hub failed")
	}

	return mq.ReplyOK(coormq.RespGetHubConnectivities(cons))
}
