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/collocations" "github.com/google/uuid" "github.com/redis/go-redis/v9" ) type CollocationsService struct { provider collocations.Provider redis *redis.Client } func NewCollocationsService(provider collocations.Provider, r *redis.Client) *CollocationsService { return &CollocationsService{provider: provider, redis: r} } func (s *CollocationsService) GenerateCollocations(ctx context.Context, userID uuid.UUID, word string, lang model.Language) (*model.CollocationsResult, error) { key := collocationsCacheKey(word, lang) ctx = WithUserID(ctx, userID) 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 result model.CollocationsResult if err := json.Unmarshal([]byte(val), &result); err != nil { log.Printf("unmarshaling cached result for %q: %v", key, err) } result.Source = model.Cache return &result, nil } result, err := s.provider.GenerateCollocations(ctx, word, lang) if err != nil { return nil, fmt.Errorf("generating collocations for %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 collocations for cache %q: %v", key, err) } else if err := s.redis.Set(ctx, key, data, 0).Err(); err != nil { log.Printf("caching collocations %q: %v", key, err) } return result, nil } func collocationsCacheKey(word string, lang model.Language) string { sum := sha256.Sum256([]byte(word)) return fmt.Sprintf("collocations:%s:%s:%s", word, lang, hex.EncodeToString(sum[:])) }