<?php

declare(strict_types=1);

namespace App\Framework\Database\Config;

use App\Framework\Config\Environment;
use App\Framework\Config\EnvKey;
use App\Framework\Database\Driver\DriverConfig;
use App\Framework\Database\Driver\DriverType;
use App\Framework\DI\Initializer;

final readonly class DatabaseConfigInitializer
{
    public function __construct(
        private Environment $env,
    ) {
    }

    #[Initializer]
    public function __invoke(): DatabaseConfig
    {
        $driverConfig = new DriverConfig(
            driverType: DriverType::from($this->env->getString(EnvKey::DB_DRIVER, 'pgsql')),
            host: $this->env->getString(EnvKey::DB_HOST, 'db'),
            port: $this->env->getInt(EnvKey::DB_PORT, 3306),
            database: $this->env->getRequired(EnvKey::DB_DATABASE),
            username: $this->env->getRequired(EnvKey::DB_USERNAME),
            password: $this->env->getRequired(EnvKey::DB_PASSWORD),
            charset: $this->env->getString(EnvKey::DB_CHARSET, 'utf8mb4'),
        );

        $poolConfig = new PoolConfig(
            enabled: true,
            maxConnections: 10,
            minConnections: 2
        );

        $readWriteConfig = new ReadWriteConfig(
            enabled: false, // Disabled by default, can be enabled via env vars
            readConnections: []
        );

        return new DatabaseConfig(
            driverConfig: $driverConfig,
            poolConfig: $poolConfig,
            readWriteConfig: $readWriteConfig,
        );
    }
}
