<?php

declare(strict_types=1);

namespace App\Framework\Redis;

use App\Framework\Config\Environment;
use App\Framework\Config\EnvKey;

/**
 * Configuration for Redis connections
 */
final readonly class RedisConfig
{
    public function __construct(
        public string $host = 'redis',
        public int $port = 6379,
        public ?string $password = null,
        public int $database = 0,
        public float $timeout = 1.0,
        public float $readWriteTimeout = 1.0,
        public string $scheme = 'tcp',
        public ?string $keyPrefix = null,
        public array $options = []
    ) {
    }

    /**
     * Create configuration from environment variables or defaults
     */
    public static function fromEnvironment(Environment $env): self
    {
        return new self(
            host: $env->get(EnvKey::REDIS_HOST, 'redis'),
            port: $env->get(EnvKey::REDIS_PORT, 6379),
            password: $env->get(EnvKey::REDIS_PASSWORD, null),
            database: 0,
            timeout: 1.0,
            readWriteTimeout: 1.0,
            keyPrefix: $env->get(EnvKey::REDIS_PREFIX, null)
        );
    }

    /**
     * Create a new config with different database
     */
    public function withDatabase(int $database): self
    {
        return new self(
            host: $this->host,
            port: $this->port,
            password: $this->password,
            database: $database,
            timeout: $this->timeout,
            readWriteTimeout: $this->readWriteTimeout,
            scheme: $this->scheme,
            keyPrefix: $this->keyPrefix,
            options: $this->options
        );
    }

    /**
     * Convert to Predis connection parameters
     */
    public function toConnectionParameters(): array
    {
        $params = [
            'scheme' => $this->scheme,
            'host' => $this->host,
            'port' => $this->port,
            'database' => $this->database,
            'timeout' => $this->timeout,
            'read_write_timeout' => $this->readWriteTimeout,
        ];

        if ($this->password) {
            $params['password'] = $this->password;
        }

        return array_merge($params, $this->options);
    }
}
