<?php
declare(strict_types=1);

namespace FreshCloud\Mail\Config;

final readonly class EnvConfig implements ConfigInterface
{
    public function __construct(private string $prefix = '')
    {
    }

    public function get(string $key, mixed $default = null): mixed
    {
        $envKey = $this->prefix . $key;
        $value = getenv($envKey);

        if ($value === false) {
            return $default;
        }

        return $value;
    }

    public function set(string $key, mixed $value): void
    {
        $envKey = $this->prefix . $key;
        $_ENV[$envKey] = $value;
        putenv("$envKey=$value");
    }

    public function has(string $key): bool
    {
        $envKey = $this->prefix . $key;
        return getenv($envKey) !== false;
    }

    public function all(): array
    {
        $prefixLength = strlen($this->prefix);
        $result = [];
        
        foreach ($_ENV as $key => $value) {
            if (str_starts_with($key, $this->prefix)) {
                $result[substr($key, $prefixLength)] = $value;
            }
        }
        
        return $result;
    }
}