// Package redisclient provides the Redis client helpers used by Gateway
// runtime wiring. The helpers wrap `pkg/redisconn` so the runtime keeps the
// same construction surface as the other Galaxy services.
package redisclient

import (
	"context"
	"fmt"

	"galaxy/gateway/internal/telemetry"
	"galaxy/redisconn"

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

// NewClient constructs one Redis client from cfg using the shared
// `pkg/redisconn` helper, which enforces the master/replica/password env-var
// shape.
func NewClient(cfg redisconn.Config) *redis.Client {
	return redisconn.NewMasterClient(cfg)
}

// InstrumentClient attaches Redis tracing and metrics exporters to client
// when telemetryRuntime is available.
func InstrumentClient(client *redis.Client, telemetryRuntime *telemetry.Runtime) error {
	if client == nil {
		return fmt.Errorf("instrument redis client: nil client")
	}
	if telemetryRuntime == nil {
		return nil
	}

	return redisconn.Instrument(
		client,
		redisconn.WithTracerProvider(telemetryRuntime.TracerProvider()),
		redisconn.WithMeterProvider(telemetryRuntime.MeterProvider()),
	)
}

// Ping performs the startup Redis connectivity check bounded by
// cfg.OperationTimeout.
func Ping(ctx context.Context, cfg redisconn.Config, client *redis.Client) error {
	if client == nil {
		return fmt.Errorf("ping redis: nil client")
	}

	pingCtx, cancel := context.WithTimeout(ctx, cfg.OperationTimeout)
	defer cancel()

	if err := client.Ping(pingCtx).Err(); err != nil {
		return fmt.Errorf("ping redis: %w", err)
	}

	return nil
}
