package auth

import (
	"encoding/json"
	"time"

	"git.links123.net/links123.com/pkg/utils"
	"github.com/go-redis/redis"
)

type (
	RedisSessionStore struct{ client *redis.Client }

	item map[string]interface{}
)

func NewRedisSessionStore(address string, password string) *RedisSessionStore {
	session := &RedisSessionStore{}
	session.client = redis.NewClient(&redis.Options{
		Addr:     address,
		Password: password,
	})

	if err := session.client.Ping().Err(); err != nil {
		panic(err)
	}

	return session
}

func (rss *RedisSessionStore) StoreJwtToken(token string, uid int64, timeout int64) error {
	k := utils.Md5(token)
	v := item{"user_id": uid, "created": time.Now().Unix()}

	return rss.client.Set(k, v, time.Duration(timeout)*time.Second).Err()
}

func (rss *RedisSessionStore) IsExistsJwtToken(token string) bool {
	k := utils.Md5(token)

	return rss.client.Exists(k).Val() == 1
}

func (rss *RedisSessionStore) DeleteJwtToken(token string) bool {
	k := utils.Md5(token)

	return rss.client.Del(k).Val() == 1
}

func (i item) MarshalBinary() (data []byte, err error) {
	return json.Marshal(i)
}
