// Filename: internal/store/factory.go
package store

import (
	"context"
	"fmt"
	"gemini-balancer/internal/config"

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

// NewStore creates a new store based on the application configuration.
func NewStore(cfg *config.Config, logger *logrus.Logger) (Store, error) {
	if cfg.Redis.DSN != "" {
		opts, err := redis.ParseURL(cfg.Redis.DSN)
		if err != nil {
			return nil, fmt.Errorf("failed to parse redis DSN: %w", err)
		}
		client := redis.NewClient(opts)
		if err := client.Ping(context.Background()).Err(); err != nil {
			logger.WithError(err).Warnf("WARN: Failed to connect to Redis (%s), falling back to in-memory store. Error: %v", cfg.Redis.DSN, err)
			return NewMemoryStore(logger), nil
		}
		logger.Info("Successfully connected to Redis. Using Redis as store.")
		return NewRedisStore(client, logger), nil
	}
	logger.Info("INFO: Redis DSN not configured, falling back to in-memory store.")
	return NewMemoryStore(logger), nil
}
