package processor

import (
	"encoding/json"
	"fmt"

	"be.ems/src/framework/logger"
	"be.ems/src/framework/vo/result"
	neDataModel "be.ems/src/modules/network_data/model"
	neDataService "be.ems/src/modules/network_data/service"
	neService "be.ems/src/modules/network_element/service"
)

// GetUEConnectByAMF 获取UE会话事件-AMF
func GetUEConnectByAMF(requestID string, data any) ([]byte, error) {
	msgByte, _ := json.Marshal(data)
	var query neDataModel.UEEventAMFQuery
	err := json.Unmarshal(msgByte, &query)
	if err != nil {
		logger.Warnf("ws processor GetUEConnectByAMF err: %s", err.Error())
		return nil, fmt.Errorf("query data structure error")
	}

	// 查询网元获取IP
	neInfo := neService.NewNeInfo.SelectNeInfoByNeTypeAndNeID("AMF", query.NeID)
	if neInfo.NeId != query.NeID || neInfo.IP == "" {
		return nil, fmt.Errorf("not fount neId info")
	}
	query.RmUID = neInfo.RmUID

	rows, total := neDataService.NewUEEventAMF.SelectPage(query)
	resultByte, err := json.Marshal(result.Ok(map[string]any{
		"requestId": requestID,
		"data":      map[string]any{"rows": rows, "total": total},
	}))
	return resultByte, err
}

// GetUEConnectByMME 获取UE会话事件-MME
func GetUEConnectByMME(requestID string, data any) ([]byte, error) {
	msgByte, _ := json.Marshal(data)
	var query neDataModel.UEEventMMEQuery
	err := json.Unmarshal(msgByte, &query)
	if err != nil {
		logger.Warnf("ws processor GetUEConnectByMME err: %s", err.Error())
		return nil, fmt.Errorf("query data structure error")
	}

	// 查询网元获取IP
	neInfo := neService.NewNeInfo.SelectNeInfoByNeTypeAndNeID("MME", query.NeID)
	if neInfo.NeId != query.NeID || neInfo.IP == "" {
		return nil, fmt.Errorf("not fount neId info")
	}
	query.RmUID = neInfo.RmUID

	rows, total := neDataService.NewUEEventMME.SelectPage(query)
	resultByte, err := json.Marshal(result.Ok(map[string]any{
		"requestId": requestID,
		"data":      map[string]any{"rows": rows, "total": total},
	}))
	return resultByte, err
}
