<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\DI\Resolver;

use PpPhp\Core\Platform\DI\Contracts\ContainerInterface;
use PpPhp\Core\Platform\DI\Exceptions\ResolutionException;
use PpPhp\Core\Platform\DI\Reflection\ReflectionService;

final class ConstructorResolver
{
    public function __construct(
        private readonly ReflectionService $reflection,
        private readonly ParameterResolver $parameters
    ) {}

    public function build(string $className, ContainerInterface $container): object
    {
        $metadata = $this->reflection->inspect($className);

        if (!$metadata->instantiable()) {
            throw new ResolutionException('Class is not instantiable: ' . $className);
        }

        $constructor = $metadata->constructor();

        if (!$constructor || $constructor->parameters() === []) {
            return new $className();
        }

        $args = [];

        foreach ($constructor->parameters() as $parameter) {
            $args[] = $this->parameters->resolve($parameter, $container);
        }

        return new $className(...$args);
    }
}
