<?php

declare(strict_types=1);

namespace App\Core;

/**
 * Autoloader
 *
 * Minimal PSR-4 autoloader for the App\ namespace, mapped to /app.
 * composer.json declares the same mapping ("App\\": "app/") so that
 * once `composer install` has run, Composer's generated autoloader
 * (vendor/autoload.php) takes over transparently — this class is only
 * ever registered as a fallback when vendor/autoload.php isn't present
 * yet (see public/index.php), so the app is never dead in the water
 * just because Composer hasn't been run on a fresh checkout.
 *
 * Third-party packages (PHPMailer, etc.) always require a real
 * `composer install` — this autoloader only resolves App\* classes.
 */
/**
 * Autoloader
 *
 * Minimal PSR-4 autoloader supporting multiple namespace prefixes
 * (App\ => app/, Database\Seeders\ => database/seeders/, ...). Composer
 * is still used for third-party packages — see composer.json — but the
 * app's own classes never block on `composer install` having been run.
 * Once vendor/autoload.php exists, public/index.php prefers it and
 * this class is never even loaded.
 */
final class Autoloader
{
    /** @var array<string,string> PSR-4 prefix => base directory (absolute path) */
    private static array $prefixes = [];

    public static function register(string $baseDir): void
    {
        $baseDir = rtrim($baseDir, '/');

        self::addNamespace('App\\', $baseDir . '/app');
        self::addNamespace('Database\\Seeders\\', $baseDir . '/database/seeders');

        spl_autoload_register([self::class, 'resolve']);
    }

    public static function addNamespace(string $prefix, string $directory): void
    {
        self::$prefixes[$prefix] = rtrim($directory, '/');
    }

    public static function resolve(string $class): void
    {
        foreach (self::$prefixes as $prefix => $directory) {
            if (!str_starts_with($class, $prefix)) {
                continue;
            }

            $relative = substr($class, strlen($prefix));
            $segments = explode('\\', $relative);

            // Our on-disk directories are lowercase (app/core, app/controllers,
            // database/seeders, ...) while namespace segments follow PSR-4's
            // usual StudlyCase convention. Lowercase every directory segment
            // but leave the final segment (the class/file name) untouched.
            // $classFile = array_pop($segments);
            // $segments = array_map('strtolower', $segments);
            // $segments[] = $classFile;

            // $path = $directory . '/' . implode('/', $segments) . '.php';
            
            
            $classFile = array_pop($segments);
            $segments[] = $classFile;
            
            $path = $directory . '/' . implode('/', $segments) . '.php';



            if (is_file($path)) {
                require $path;

                return;
            }
        }
    }
}
