<?php

declare(strict_types=1);

namespace Tricks\LaravelTools;

use Composer\Autoload\ClassLoader;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use ReflectionClass;

final class EloquentModels
{
    /**
     * @return Collection<int, Model>
     */
    public static function get(): Collection
    {
        /** @var ClassLoader $firstRegisteredLoader */
        $firstRegisteredLoader = Arr::first(ClassLoader::getRegisteredLoaders());

        return collect($firstRegisteredLoader->getClassMap())
            ->keys()
            ->filter(fn (string $className): bool => Str::contains($className, 'App\\') && class_exists($className))
            ->map(fn (string $className): ReflectionClass => new ReflectionClass($className))
            ->filter(fn (ReflectionClass $reflection): bool => $reflection->isSubclassOf(Model::class))
            ->map(fn (ReflectionClass $reflection): Model => $reflection->newInstance());
    }
}
