package fetchlink

import (
	"encoding/json"
	"fmt"

	"be.ems/src/framework/logger"
	"be.ems/src/framework/utils/fetch"
	"be.ems/src/modules/ne/model"
)

// NSSFSubInfoList NSSF在线列表信息
//
// 返回结果 {"rows":[],"total":0}
func NSSFSubInfoList(neInfo model.NeInfo) (map[string]any, error) {
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/ueManagement/v1/elementType/nssf/objectType/subscriptions", neInfo.IP, neInfo.Port)
	resBytes, err := fetch.Get(neUrl, nil, 60_000)
	if err != nil {
		logger.Warnf("NSSFSubInfo Get \"%s\"", neUrl)
		logger.Errorf("NSSFSubInfo %s", err.Error())
		return nil, fmt.Errorf("NeService NSSF API Error")
	}

	// 序列化结果
	// {
	//     "data": [
	//         {
	//             "subscriptionId": "460302072701181",
	//             "event": "460302072701181",
	//             "nfNssaiAvailabilityUri": "0460302072701181@nai.epc.mnc030.mcc460.3gppnetwork.org"
	//         }
	//     ]
	// }
	var resData map[string]any
	err = json.Unmarshal(resBytes, &resData)
	if err != nil {
		logger.Errorf("NSSFSubInfo Unmarshal %s", err.Error())
		return nil, err
	}

	// 固定返回字段，方便前端解析
	if v, ok := resData["data"]; ok && v != nil {
		resData["rows"] = v.([]any)
		resData["total"] = len(v.([]any))
		delete(resData, "data")
	} else {
		resData["rows"] = []any{}
		resData["total"] = 0
	}
	return resData, nil
}

// NSSFAvailableAMFList NSSF装载AMF信息
//
// 返回结果 {"rows":[],"total":0}
func NSSFAvailableAMFList(neInfo model.NeInfo) (map[string]any, error) {
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/ueManagement/v1/elementType/nssf/objectType/availableAMFs", neInfo.IP, neInfo.Port)
	resBytes, err := fetch.Get(neUrl, nil, 60_000)
	if err != nil {
		logger.Warnf("NSSFAvailableAMFList Get \"%s\"", neUrl)
		logger.Errorf("NSSFAvailableAMFList %s", err.Error())
		return nil, fmt.Errorf("NeService NSSF API Error")
	}

	// 序列化结果
	// {
	//     "data": [
	//         {
	//             "nfId": "001",
	//             "amfSetId": "001"
	//         },
	//         {
	//             "nfId": "002",
	//             "amfSetId": "[001,002]"
	//         }
	//     ]
	// }
	var resData map[string]any
	err = json.Unmarshal(resBytes, &resData)
	if err != nil {
		logger.Errorf("NSSFAvailableAMFList Unmarshal %s", err.Error())
		return nil, err
	}

	// 固定返回字段，方便前端解析
	if v, ok := resData["data"]; ok && v != nil {
		resData["rows"] = v.([]any)
		resData["total"] = len(v.([]any))
		delete(resData, "data")
	} else {
		resData["rows"] = []any{}
		resData["total"] = 0
	}
	return resData, nil
}
