package processor

import (
	"encoding/json"
	"fmt"

	"be.ems/src/framework/logger"
	"be.ems/src/framework/vo/result"
	neService "be.ems/src/modules/network_element/service"
)

// GetNeState 获取网元服务状态
func GetNeState(requestID string, data any) ([]byte, error) {
	msgByte, _ := json.Marshal(data)
	var querys struct {
		NeType string `json:"neType" form:"neType" binding:"required"`
		NeID   string `json:"neId" form:"neId" binding:"required"`
	}
	err := json.Unmarshal(msgByte, &querys)
	if err != nil {
		logger.Warnf("ws processor GetUPFTotalFlow err: %s", err.Error())
		return nil, fmt.Errorf("query data structure error")
	}

	if querys.NeType == "" || querys.NeID == "" {
		return nil, fmt.Errorf("query neType any neId empty")
	}

	// 查询网元获取IP
	neInfo := neService.NewNeInfoImpl.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeID)
	if neInfo.NeId != querys.NeID || neInfo.IP == "" {
		return nil, fmt.Errorf("no matching network element information found")
	}

	// 网元直连
	resData, err := neService.NeState(neInfo)
	if err != nil {
		resultByte, err := json.Marshal(result.Ok(map[string]any{
			"requestId": requestID,
			"data": map[string]any{
				"online": false,
				"neId":   neInfo.NeId,
				"neName": neInfo.NeName,
				"neType": neInfo.NeType,
				"neIP":   neInfo.IP,
			},
		}))
		return resultByte, err
	}

	resData["online"] = true
	resultByte, err := json.Marshal(result.Ok(map[string]any{
		"requestId": requestID,
		"data":      resData,
	}))
	return resultByte, err
}
