package auth

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"

	"github.com/redis/go-redis/v9"
)

type SessionReader interface {
	// GetSession returns ErrSessionNotFound if no valid session.
	GetSession(ctx context.Context, sessionToken string) (*Session, error)
}

type sessionReaderImpl struct {
	redisClient *redis.Client
}

// Exposes the concrete type so authServiceImpl can embed it without
// hiding redisClient behind the SessionReader interface.
func newSessionReader(redisClient *redis.Client) *sessionReaderImpl {
	return &sessionReaderImpl{redisClient: redisClient}
}

func NewSessionReader(redisClient *redis.Client) SessionReader {
	return newSessionReader(redisClient)
}

func (r *sessionReaderImpl) GetSession(ctx context.Context, token string) (*Session, error) {
	sessionInfo, err := r.redisClient.Get(ctx, token).Result()
	if err != nil {
		if errors.Is(err, redis.Nil) {
			return nil, ErrSessionNotFound
		}
		return nil, fmt.Errorf("error getting session: %w", err)
	}

	var session Session
	err = json.Unmarshal([]byte(sessionInfo), &session)

	return &session, nil
}
