package cdr

import (
	"encoding/json"
	"io"
	"net/http"

	"nms_nbi/lib/dborm"
	"nms_nbi/lib/global"
	"nms_nbi/lib/log"
	"nms_nbi/lib/services"
	"nms_nbi/restagent/config"
	wsService "nms_nbi/src/modules/ws/service"
)

var (
	UriCDREvent = config.DefaultUriPrefix + "/cdrManagement/v1/elementType/{elementTypeValue}/objectType/cdrEvent"
	UriCDRFile  = config.DefaultUriPrefix + "/cdrManagement/v1/elementType/{elementTypeValue}/objectType/cdrFile"

	CustomUriCDREvent = config.UriPrefix + "/cdrManagement/v1/elementType/{elementTypeValue}/objectType/cdrEvent"
	CustomUriCDRFile  = config.UriPrefix + "/cdrManagement/v1/elementType/{elementTypeValue}/objectType/cdrFile"
)

type CDREvent struct {
	NeType    string         `json:"neType" xorm:"ne_type"`
	NeName    string         `json:"neName" xorm:"ne_name"`
	RmUID     string         `json:"rmUID" xorm:"rm_uid"`
	Timestamp int            `json:"timestamp" xorm:"timestamp"`
	CDR       map[string]any `json:"CDR" xorm:"cdr_json"`
}

func PostCDREventFromNF(w http.ResponseWriter, r *http.Request) {
	log.Info("PostCDREventFromNF processing... ")

	//	body, err := io.ReadAll(io.LimitReader(r.Body, global.RequestBodyMaxLen))
	body, err := io.ReadAll(io.LimitReader(r.Body, global.RequestBodyMaxLen))
	if err != nil {
		log.Error("Faile to io.ReadAll: ", err)
		services.ResponseNotFound404UriNotExist(w, r)
		return
	}

	cdrEvent := new(CDREvent)
	err = json.Unmarshal(body, &cdrEvent)
	if cdrEvent.NeType == "" || err != nil {
		log.Error("Failed to Unmarshal cdrEvent:", err)
		services.ResponseInternalServerError500ProcessError(w, err)
		return
	}
	log.Trace("cdrEvent:", cdrEvent)

	affected, err := dborm.XormInsertTableOne("cdr_event", cdrEvent)
	if err != nil && affected <= 0 {
		log.Error("Failed to insert cdr_event:", err)
		services.ResponseInternalServerError500ProcessError(w, err)
		return
	}

	// 推送到ws订阅组
	if v, ok := cdrEvent.CDR["recordType"]; ok {
		if v == "MOC" || v == "MTSM" {
			wsService.NewWSSendImpl.ByGroupID(wsService.GROUP_IMS_CDR, cdrEvent)
		}
	}

	services.ResponseStatusOK204NoContent(w)
}
