// Package cache provides a small read-through cache seam. Redis is the only
// backend; Redis never stores business truth (architecture.md §7) — it only
// short-circuits recomputation (e.g. dashboard KPIs). An empty/disabled client
// yields a Nop that falls through to the underlying store.
package cache

import (
	"context"
	"time"

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

// Cache reads and writes JSON-serializable payloads by key.
type Cache interface {
	Get(ctx context.Context, key string) (string, bool, error)
	Set(ctx context.Context, key string, value string, ttl time.Duration) error
}

// Redis implements Cache on a go-redis client. A nil client disables caching.
type Redis struct {
	rdb *redis.Client
}

func New(rdb *redis.Client) *Redis {
	if rdb == nil {
		return nil
	}
	return &Redis{rdb: rdb}
}

func (c *Redis) Get(ctx context.Context, key string) (string, bool, error) {
	v, err := c.rdb.Get(ctx, key).Result()
	if err == redis.Nil {
		return "", false, nil
	}
	if err != nil {
		return "", false, err
	}
	return v, true, nil
}

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

// Nop is a pass-through cache (no-op) used when Redis is disabled.
type Nop struct{}

func (Nop) Get(context.Context, string) (string, bool, error) { return "", false, nil }
func (Nop) Set(context.Context, string, string, time.Duration) error {
	return nil
}
