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"
	neInfoService "be.ems/src/modules/network_element/service"
)

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

	// 查询网元信息 rmUID
	neInfo := neInfoService.NewNeInfo.SelectNeInfoByNeTypeAndNeID(query.NeType, query.NeID)
	if neInfo.NeId != query.NeID || neInfo.IP == "" {
		return nil, fmt.Errorf("query neinfo not found")
	}
	query.RmUID = neInfo.RmUID

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

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

	// 查询网元信息 rmUID
	neInfo := neInfoService.NewNeInfo.SelectNeInfoByNeTypeAndNeID(query.NeType, query.NeID)
	if neInfo.NeId != query.NeID || neInfo.IP == "" {
		return nil, fmt.Errorf("query neinfo not found")
	}
	query.RmUID = neInfo.RmUID

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

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

	// 查询网元信息 rmUID
	neInfo := neInfoService.NewNeInfo.SelectNeInfoByNeTypeAndNeID(query.NeType, query.NeID)
	if neInfo.NeId != query.NeID || neInfo.IP == "" {
		return nil, fmt.Errorf("query neinfo not found")
	}
	query.RmUID = neInfo.RmUID

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