// Package cache wraps Redis with the small surface the gateway needs.
//
// Every cached value is scoped to an Emby user id, because "what's on the home screen"
// is per-user. Mutations (favourite, watched, playback stopped) drop that user's keys
// so the next request re-reads Emby rather than serving a stale row.
package cache

import (
	"context"
	"errors"
	"fmt"
	"time"

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

// ErrMiss means the key was absent — an ordinary outcome, not a failure.
var ErrMiss = errors.New("cache: miss")

type Cache struct {
	rdb *redis.Client
}

func Open(redisURL string) (*Cache, error) {
	opts, err := redis.ParseURL(redisURL)
	if err != nil {
		return nil, fmt.Errorf("cache: parse url: %w", err)
	}
	return &Cache{rdb: redis.NewClient(opts)}, nil
}

func (c *Cache) Close() error { return c.rdb.Close() }

func (c *Cache) Ping(ctx context.Context) error { return c.rdb.Ping(ctx).Err() }

func (c *Cache) Get(ctx context.Context, key string) ([]byte, error) {
	b, err := c.rdb.Get(ctx, key).Bytes()
	if errors.Is(err, redis.Nil) {
		return nil, ErrMiss
	}
	if err != nil {
		return nil, err
	}
	return b, nil
}

func (c *Cache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
	return c.rdb.Set(ctx, key, value, ttl).Err()
}

func (c *Cache) Delete(ctx context.Context, keys ...string) error {
	if len(keys) == 0 {
		return nil
	}
	return c.rdb.Del(ctx, keys...).Err()
}

// InvalidateUser drops every cached view belonging to one Emby user.
//
// SCAN rather than KEYS so a large keyspace never blocks Redis; the key count here is
// small, but the habit costs nothing.
func (c *Cache) InvalidateUser(ctx context.Context, userID string) error {
	pattern := fmt.Sprintf("u:%s:*", userID)
	var cursor uint64
	for {
		keys, next, err := c.rdb.Scan(ctx, cursor, pattern, 200).Result()
		if err != nil {
			return err
		}
		if len(keys) > 0 {
			if err := c.rdb.Del(ctx, keys...).Err(); err != nil {
				return err
			}
		}
		if next == 0 {
			return nil
		}
		cursor = next
	}
}

// UserKey builds the namespaced key used by everything user-scoped.
func UserKey(userID, view string) string { return fmt.Sprintf("u:%s:%s", userID, view) }

// RecommendationsKey sits in its own `r:` namespace on purpose.
//
// Recommendations cost several Emby queries to build, so they survive ordinary user-view
// invalidation and expire on their own slow-moving daily cadence.
func RecommendationsKey(userID string) string { return fmt.Sprintf("r:%s:rows:v3", userID) }

// SessionKey caches a token→session lookup, keyed by token hash (never the token).
func SessionKey(tokenHashHex string) string { return "sess:" + tokenHashHex }
