package fetchlink

import (
	"encoding/json"
	"fmt"
	"strings"

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

// NeTraceAdd 网元跟踪任务新增
func NeTraceAdd(neInfo model.NeInfo, data any) (map[string]any, error) {
	// 跟踪任务创建
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/traceManagement/v2/%s/subscriptions", neInfo.IP, neInfo.Port, neInfo.NeType)
	resBytes, err := fetch.PostJSON(neUrl, data, nil)
	var resData map[string]any
	if err != nil {
		errStr := err.Error()
		if !(strings.HasPrefix(errStr, "201") || strings.HasPrefix(errStr, "400")) {
			logger.Warnf("NeTraceAdd POST \"%s\"", neUrl)
			logger.Errorf("NeTraceAdd %s", errStr)
			return nil, fmt.Errorf("NeService Trace Add API Error")
		}
	}

	// 200 成功无数据时
	if len(resBytes) == 0 {
		return resData, nil
	}

	// 序列化结果
	err = json.Unmarshal(resBytes, &resData)
	if err != nil {
		logger.Errorf("NeTraceAdd Unmarshal %s", err.Error())
		return nil, err
	}
	return resData, nil
}

// NeTraceDelete 网元跟踪任务删除
func NeTraceDelete(neInfo model.NeInfo, traceId string) (map[string]any, error) {
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/traceManagement/v2/%s/subscriptions?id=%s", neInfo.IP, neInfo.Port, neInfo.NeType, traceId)
	resBytes, err := fetch.Delete(neUrl, nil)
	var resData map[string]any
	if err != nil {
		errStr := err.Error()
		if strings.HasPrefix(errStr, "201") || strings.HasPrefix(errStr, "204") {
			return resData, nil
		}
		logger.Warnf("NeTraceDelete Delete \"%s\"", neUrl)
		logger.Errorf("NeTraceDelete %s", errStr)
		return nil, fmt.Errorf("NeService Trace Delete API Error")
	}

	// 200 成功无数据时
	if len(resBytes) == 0 {
		return resData, nil
	}

	// 序列化结果
	err = json.Unmarshal(resBytes, &resData)
	if err != nil {
		logger.Errorf("NeTraceDelete Unmarshal %s", err.Error())
		return nil, err
	}
	return resData, nil
}
