<?php

declare(strict_types=1);

namespace RainbowDrive\Support;

final class Psr4Autoloader
{
    /**
     * @var array<string, list<string>>
     */
    private array $prefixes = [];

    public function addNamespace(string $prefix, string $baseDir): void
    {
        $normalizedPrefix = trim($prefix, '\\') . '\\';
        $normalizedBaseDir = rtrim($baseDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;

        $this->prefixes[$normalizedPrefix][] = $normalizedBaseDir;
    }

    public function register(): void
    {
        spl_autoload_register([$this, 'loadClass']);
    }

    public function loadClass(string $class): void
    {
        foreach ($this->prefixes as $prefix => $baseDirs) {
            if (!str_starts_with($class, $prefix)) {
                continue;
            }

            $relativeClass = substr($class, strlen($prefix));
            $relativePath = str_replace('\\', DIRECTORY_SEPARATOR, $relativeClass) . '.php';

            foreach ($baseDirs as $baseDir) {
                $file = $baseDir . $relativePath;
                if (is_file($file)) {
                    require $file;
                    return;
                }
            }
        }
    }
}
