package storage import ( "context" "encoding/json" "fmt" "time" "github.com/redis/go-redis/v9" "github.com/paramah/gw_telegram/internal/domain/apperror" "github.com/paramah/gw_telegram/internal/domain/entity" ) type RedisSessionStore struct { client *redis.Client ttl time.Duration } func NewRedisSessionStore(client *redis.Client, ttlHours int) *RedisSessionStore { return &RedisSessionStore{ client: client, ttl: time.Duration(ttlHours) * time.Hour, } } func sessionKey(userID int64) string { return fmt.Sprintf("session:%d", userID) } func (s *RedisSessionStore) Get(ctx context.Context, userID int64) (entity.Session, error) { data, err := s.client.Get(ctx, sessionKey(userID)).Bytes() if err == redis.Nil { return entity.Session{}, apperror.ErrSessionNotFound } if err != nil { return entity.Session{}, fmt.Errorf("redis get session: %w", err) } var session entity.Session if err := json.Unmarshal(data, &session); err != nil { return entity.Session{}, fmt.Errorf("unmarshal session: %w", err) } return session, nil } func (s *RedisSessionStore) Set(ctx context.Context, session entity.Session) error { data, err := json.Marshal(session) if err != nil { return fmt.Errorf("marshal session: %w", err) } if err := s.client.Set(ctx, sessionKey(session.UserID), data, s.ttl).Err(); err != nil { return fmt.Errorf("redis set session: %w", err) } return nil } func (s *RedisSessionStore) Delete(ctx context.Context, userID int64) error { if err := s.client.Del(ctx, sessionKey(userID)).Err(); err != nil { return fmt.Errorf("redis del session: %w", err) } return nil }