<?php
declare(strict_types=1);

namespace App\Core;

final class Autoloader
{
    private static bool $registered = false;

    private static array $prefixes = [
        'App\\Core\\'       => 'app/Core/',
        'App\\Modules\\'    => 'app/Modules/',
        'App\\Middleware\\'  => 'app/Middleware/',
        'App\\Shared\\'     => 'app/Shared/',
    ];

    public static function register(): void
    {
        if (self::$registered) {
            return;
        }

        spl_autoload_register([self::class, 'load']);
        self::$registered = true;

        $helpersPath = self::basePath() . '/app/Core/Helpers.php';
        if (file_exists($helpersPath)) {
            require_once $helpersPath;
        }
    }

    public static function load(string $class): void
    {
        foreach (self::$prefixes as $prefix => $dir) {
            if (strpos($class, $prefix) === 0) {
                $relativeClass = substr($class, strlen($prefix));
                $file = self::basePath() . '/' . $dir . str_replace('\\', '/', $relativeClass) . '.php';

                if (file_exists($file)) {
                    require_once $file;
                    return;
                }
            }
        }
    }

    public static function basePath(): string
    {
        return dirname(__DIR__, 2);
    }
}