package mf_calling

import (
	"be.ems/src/framework/i18n"
	"be.ems/src/framework/middleware"
	"be.ems/src/framework/utils/ctx"
	"be.ems/src/framework/vo/result"
	"github.com/gin-gonic/gin"

	neService "be.ems/src/modules/network_element/service"
)

// @Description Register Routes for mf calling
func Register(r *gin.RouterGroup) {

	mfCallingGroup := r.Group("/callings")
	{
		var m *MfCallingInfo
		mfCallingGroup.GET("/list",
			middleware.PreAuthorize(nil),
			m.List,
		)
	}
}

func (s *MfCallingInfo) List(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var querys struct {
		NeId       string `form:"neId" binding:"required"`
		TenantName string `form:"tenantName"`
	}
	if err := c.ShouldBindQuery(&querys); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	// 处理租户逻辑
	loginUser, _ := ctx.LoginUser(c)
	if len(loginUser.User.Roles) > 0 {
		for _, v := range loginUser.User.Roles {
			if v.RoleKey == "tenant" {
				querys.TenantName = loginUser.User.UserName
				break
			}
		}
	}

	// 查询网元信息
	neInfo := neService.NewNeInfo.SelectNeInfoByNeTypeAndNeID("MF", querys.NeId)
	if neInfo.NeId != querys.NeId || neInfo.IP == "" {
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
		return
	}
	// 1. 调用服务层方法，向网元MF发起API请求
	data, total, err := s.GetCallingInfoFromMF(neInfo)
	if err != nil {
		c.JSON(500, result.ErrMsg(err.Error()))
		return
	}

	c.JSON(200, result.Ok(gin.H{
		"total": total,
		"data":  data,
	}))
}
