package fetchlink

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

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

// AlarmHistory 告警历史记录
func AlarmHistory(neInfo model.NeInfo) ([]map[string]any, error) {
	// 网元参数配置信息
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/faultManagement/v1/elementType/%s/objectType/alarms", neInfo.IP, neInfo.Port, strings.ToLower(neInfo.NeType))
	resBytes, err := fetch.Get(neUrl, nil, 60_000)
	var resData []map[string]any
	if err != nil {
		errStr := err.Error()
		logger.Warnf("AlarmHistory Get \"%s\"", neUrl)
		if !(strings.HasPrefix(errStr, "201") || strings.HasPrefix(errStr, "202") || strings.HasPrefix(errStr, "204")) {
			logger.Errorf("AlarmHistory %s", err.Error())
			return nil, fmt.Errorf("NeService Alarm History Info API Error")
		}
	}

	if len(resBytes) == 0 {
		return resData, nil
	}

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