package service

import (
	"encoding/json"
	"fmt"

	"github.com/tsmask/go-oam"

	neService "be.ems/src/modules/ne/service"
	neDataModel "be.ems/src/modules/ne_data/model"
	neDataService "be.ems/src/modules/ne_data/service"
	wsService "be.ems/src/modules/ws/service"
)

// 实例化服务层 CDR 结构体
var NewCDR = &CDR{
	neInfoService:   neService.NewNeInfo,
	wsService:       wsService.NewWSSend,
	cdrEventService: neDataService.NewCDREvent,
}

// CDR 消息处理
type CDR struct {
	neInfoService   *neService.NeInfo
	wsService       *wsService.WSSend
	cdrEventService *neDataService.CDREvent // CDR会话事件服务
}

// Resolve 接收处理
func (s *CDR) Resolve(c oam.CDR) error {
	if c.Data == nil {
		return fmt.Errorf("cdr data is nil")
	}
	// 是否存在网元
	neInfo := s.neInfoService.FindByRmuid(c.NeUid)
	if neInfo.NeType == "" || neInfo.RmUID != c.NeUid {
		return fmt.Errorf("resolve cdr network element does not exist %s", c.NeUid)
	}

	cdrByte, _ := json.Marshal(c.Data)
	cdrEvent := neDataModel.CDREvent{
		NeType:    neInfo.NeType,
		NeName:    neInfo.NeName,
		RmUid:     neInfo.RmUID,
		Timestamp: c.RecordTime,
		CdrJson:   string(cdrByte),
		CreatedAt: c.RecordTime,
	}
	insertId := s.cdrEventService.Insert(cdrEvent)
	if insertId <= 0 {
		return fmt.Errorf("add cdr data fail")
	}
	cdrEvent.ID = insertId

	// 推送到ws订阅组
	switch neInfo.NeType {
	case "IMS":
		dataMap := c.Data.(map[string]any)
		v, ok := dataMap["recordType"]
		if ok && (v == "MOC" || v == "MTSM") {
			s.wsService.ByGroupID(fmt.Sprintf("%s_%s", wsService.GROUP_IMS_CDR, neInfo.NeId), cdrEvent)
		}
	case "SMF":
		s.wsService.ByGroupID(fmt.Sprintf("%s_%s", wsService.GROUP_SMF_CDR, neInfo.NeId), cdrEvent)
	case "SMSC":
		s.wsService.ByGroupID(fmt.Sprintf("%s_%s", wsService.GROUP_SMSC_CDR, neInfo.NeId), cdrEvent)
	case "SGWC":
		s.wsService.ByGroupID(fmt.Sprintf("%s_%s", wsService.GROUP_SGWC_CDR, neInfo.NeId), cdrEvent)
	}
	return nil
}
