package Nredis

import (
	l4g "proxy/logger"
	"strconv"
)

func RdbSetAlertSmsRecord(alertId int, serviceNbr, smsContent string) error {
	key := "AlertSms:"+serviceNbr+":"+strconv.Itoa(alertId)
	err := rdb.Set(ctx, key, smsContent, 0).Err()
	if err != nil {
		l4g.RedisLog.Errorf("Set %s, err: %v", key, err)
	} else {
		l4g.RedisLog.Debugf("Set %s, err: %s", key, smsContent)
		sadd := rdb.SAdd(ctx, "Msg2OcsSet", key)
		if sadd.Err() != nil {
			l4g.RedisLog.Errorf("SAdd Msg2OcsSet %s, err: %v", key, sadd.Err())
			return sadd.Err()
		} else {
			l4g.RedisLog.Debugf("SAdd Msg2OcsSet %s", key)
		}
	}

	return err
}

func RdbGetAlertSmsContent(key string) string {
	var sms string
	var err error
	sms, err = rdb.Get(ctx, key).Result()
	if err != nil {
		return ""
	} else {
		return sms
	}
}

func RdbScanAlertSmsRecord() []string {
	var cursor uint64= 0
	var keysFound []string
	for {
		keys, cursor, err := rdb.SScan(ctx, "Msg2OcsSet", cursor, "", 50).Result()
		if err != nil {
			l4g.RedisLog.Errorf("SScan Msg2OcsSet, err: %v", err)
			break
		}

		keysFound = append(keysFound, keys...)

		if cursor == 0 {
			break
		} else {
			break
		}
	}

	return keysFound
}

func RdsDelMsg2OcsKey(key string) {
	_ = rdb.SRem(ctx, "Msg2OcsSet", key)
	_ = rdb.Del(ctx, key).Err()
}