<?php

declare(strict_types=1);

namespace App\Core;

use RuntimeException;

final class Config
{
    private static ?array $config = null;

    public static function all(): array
    {
        if (self::$config !== null) {
            return self::$config;
        }

        $configFile = APP_PATH . '/config.php';
        if (!is_file($configFile)) {
            throw new RuntimeException('Configuration file not found.');
        }

        $config = require $configFile;
        if (!is_array($config)) {
            throw new RuntimeException('Configuration must return an array.');
        }

        self::$config = $config;
        return self::$config;
    }

    public static function get(string $key, mixed $default = null): mixed
    {
        $value = self::all();
        foreach (explode('.', $key) as $segment) {
            if (!is_array($value) || !array_key_exists($segment, $value)) {
                return $default;
            }
            $value = $value[$segment];
        }

        return $value;
    }
}
