package redisconn

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

// NewMasterClient builds the master Redis client from cfg using the
// conservative options shared by the existing service publishers
// (`Protocol: 2`, `DisableIdentity: true`, dial/read/write timeouts bound to
// cfg.OperationTimeout).
//
// NewMasterClient does not validate cfg; callers are expected to call
// Config.Validate (or LoadFromEnv which already does) before invoking this.
func NewMasterClient(cfg Config) *redis.Client {
	return redis.NewClient(buildOptions(cfg.MasterAddr, cfg))
}

// NewReplicaClients builds one Redis client per replica address. It returns
// nil when no replicas are configured; callers treat that as "no replicas
// wired".
func NewReplicaClients(cfg Config) []*redis.Client {
	if len(cfg.ReplicaAddrs) == 0 {
		return nil
	}
	clients := make([]*redis.Client, 0, len(cfg.ReplicaAddrs))
	for _, addr := range cfg.ReplicaAddrs {
		clients = append(clients, redis.NewClient(buildOptions(addr, cfg)))
	}
	return clients
}

func buildOptions(addr string, cfg Config) *redis.Options {
	return &redis.Options{
		Addr:            addr,
		Password:        cfg.Password,
		DB:              cfg.DB,
		Protocol:        2,
		DisableIdentity: true,
		DialTimeout:     cfg.OperationTimeout,
		ReadTimeout:     cfg.OperationTimeout,
		WriteTimeout:    cfg.OperationTimeout,
	}
}
