package event

import (
	"encoding/json"
	"io"
	"time"

	"be.ems/lib/dborm"
	"be.ems/lib/global"
	"be.ems/lib/log"
	"be.ems/lib/services"
	wsService "be.ems/src/modules/ws/service"
	"github.com/gin-gonic/gin"
)

var (
	UriUEEvent = "/upload-ue/v1/:eventType"
)

type UEEvent 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"`
	EventType string         `json:"eventType" xorm:"event_type"`
	EventJson map[string]any `json:"eventJSON" xorm:"event_json"`
}

func PostUEEventFromAMF(c *gin.Context) {
	log.Info("PostUEEventFromAMF processing... ")

	body, err := io.ReadAll(io.LimitReader(c.Request.Body, global.RequestBodyMaxLen))
	if err != nil {
		log.Error("Failed to io.ReadAll: ", err)
		services.ResponseNotFound404UriNotExist(c.Writer, c.Request)
		return
	}

	//vars := mux.Vars(c.Request)
	eventType, ok := c.Params.Get("eventType")
	if !ok || eventType == "" {
		log.Error("eventType is empty")
		services.ResponseNotFound404UriNotExist(c.Writer, c.Request)
		return
	}
	ueEvent := new(UEEvent)
	err = json.Unmarshal(body, &ueEvent.EventJson)
	if err != nil {
		log.Error("Failed to Unmarshal ueEvent:", err)
		services.ResponseInternalServerError500ProcessError(c.Writer, err)
		return
	}
	ueEvent.NeType = "AMF"
	ueEvent.Timestamp = int(time.Now().Unix())
	ueEvent.EventType = eventType
	log.Trace("ueEvent:", ueEvent)

	affected, err := dborm.XormInsertTableOne("ue_event", ueEvent)
	if err != nil && affected <= 0 {
		log.Error("Failed to insert ue_event:", err)
		services.ResponseInternalServerError500ProcessError(c.Writer, err)
		return
	}

	// 推送到ws订阅组
	wsService.NewWSSendImpl.ByGroupID(wsService.GROUP_AMF_UE, ueEvent)

	services.ResponseStatusOK204NoContent(c.Writer)
}
