package service import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "log" "time" "github.com/dusiburg/fancy-api/internal/model" "github.com/dusiburg/fancy-api/internal/provider/dictionary" "github.com/google/uuid" "github.com/redis/go-redis/v9" ) type DictionaryService struct { provider dictionary.Provider redis *redis.Client collections *CollectionService } func NewDictionaryService(provider dictionary.Provider, r *redis.Client, collections *CollectionService) *DictionaryService { return &DictionaryService{provider: provider, redis: r, collections: collections} } func (s *DictionaryService) Lookup(ctx context.Context, userID uuid.UUID, word string, lang model.Language) (*model.DictionaryResult, error) { key := dictionaryCacheKey(word, lang) ctx = WithUserID(ctx, userID) result, err := s.lookupResult(ctx, key, word, lang) if err != nil { return nil, err } if err := s.collections.AppendToHistory(ctx, userID, lang, word); err != nil { log.Printf("appending %q to history for user %s: %v", word, userID, err) } return result, nil } func (s *DictionaryService) lookupResult(ctx context.Context, key, word string, lang model.Language) (*model.DictionaryResult, error) { val, err := s.redis.Get(ctx, key).Result() if err != nil && !errors.Is(err, redis.Nil) { log.Printf("getting key %q: %v", key, err) } if err == nil { var cached model.DictionaryResult if err := json.Unmarshal([]byte(val), &cached); err != nil { log.Printf("unmarshaling cached result for %q: %v", key, err) } else { cached.Source = model.Cache return &cached, nil } } result, err := s.provider.Lookup(ctx, word, lang) if err != nil { return nil, fmt.Errorf("lookup %q [%s]: %w", word, lang, err) } result.Source = model.Provider generatedAt := time.Now().UTC() result.GeneratedAt = &generatedAt if data, err := json.Marshal(result); err != nil { log.Printf("marshaling dictionary for cache %q: %v", key, err) } else if err := s.redis.Set(ctx, key, data, redisCacheTTL).Err(); err != nil { log.Printf("caching dictionary %q: %v", key, err) } return result, nil } func dictionaryCacheKey(word string, lang model.Language) string { sum := sha256.Sum256([]byte(word)) return fmt.Sprintf("dictionary:%s:%s:%s", word, lang, hex.EncodeToString(sum[:])) }