package cache import ( "context" "encoding/json" "errors" "fmt" "time" "github.com/redis/go-redis/v9" "mtusi2026/internal/model" ) type Cache struct { client *redis.Client ttl time.Duration } func New(client *redis.Client, ttl time.Duration) *Cache { return &Cache{ client: client, ttl: ttl, } } func key(userID, chatID string) string { return "chat:" + userID + ":" + chatID } func (c *Cache) Get(ctx context.Context, userID, chatID string) (model.Chat, bool, error) { raw, err := c.client.Get(ctx, key(userID, chatID)).Bytes() if errors.Is(err, redis.Nil) { return model.Chat{}, false, nil } if err != nil { return model.Chat{}, false, fmt.Errorf("chat cache get: %w", err) } var chat model.Chat if err := json.Unmarshal(raw, &chat); err != nil { _ = c.client.Del(ctx, key(userID, chatID)).Err() return model.Chat{}, false, nil } return chat, true, nil } func (c *Cache) Set(ctx context.Context, userID, chatID string, chat model.Chat) error { raw, err := json.Marshal(chat) if err != nil { return fmt.Errorf("chat cache marshal: %w", err) } if err := c.client.Set(ctx, key(userID, chatID), raw, c.ttl).Err(); err != nil { return fmt.Errorf("chat cache set: %w", err) } return nil } func (c *Cache) Delete(ctx context.Context, userID, chatID string) error { if err := c.client.Del(ctx, key(userID, chatID)).Err(); err != nil { return fmt.Errorf("chat cache delete: %w", err) } return nil }