package dao

import (
	"fmt"
	"time"

	"tower_api/model"
	"tower_api/pkg/util"
)

// GetSingleNoticeFromCache 从缓存中获取最新消息
func GetSingleNoticeFromCache(specialId int) string {
	key := fmt.Sprintf("%s:%d", Notice, specialId)
	result, err := Redis().Get(key).Result()
	util.CheckRedisErr(err)
	return result
}

// CacheSingleNotice 缓存最新消息
func CacheSingleNotice(noticeJson string, specialId int) {
	key := fmt.Sprintf("%s:%d", Notice, specialId)
	err := Redis().Set(key, noticeJson, 60*time.Second).Err()
	util.CheckRedisErr(err)
}

// GetSingleNotice 获取最新的公告
func GetSingleNotice(curUnix int64, specialId int) *model.Notice {
	var notice model.Notice
	err := DB().Raw(`
SELECT 
    id, title, content
FROM
    game_notice
WHERE
    type = 2 AND status = 2
        AND start_unix <= ?
		AND start_unix > 0
        AND expire_unix >= ?
		AND special_id = ?
ORDER BY id DESC
LIMIT 1;`, curUnix, curUnix, specialId).Scan(&notice).Error
	util.CheckErr(err)
	return &notice
}

func GetSpecialId(appid string) string {
	result, err := Redis().HGet(PackageSpecialId, appid).Result()
	util.CheckRedisErr(err)
	return result
}

func CacheSpecialId(appid string, specialId int) {
	pipe := Redis().Pipeline()
	pipe.HSet(PackageSpecialId, appid, specialId)
	pipe.ExpireAt(PackageSpecialId, time.Now().Add(10*time.Minute))
	_, err := pipe.Exec()
	util.CheckRedisErr(err)
}
