<?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\ParameterMetadata;

final class ParameterResolver
{
    public function resolve(ParameterMetadata $parameter, ContainerInterface $container): mixed
    {
        $type = $parameter->type();

        if ($type !== null && !$parameter->builtin()) {
            if ($container->has($type)) {
                return $container->get($type);
            }

            return $container->make($type);
        }

        if ($parameter->hasDefault()) {
            return $parameter->defaultValue();
        }

        if ($parameter->allowsNull()) {
            return null;
        }

        throw new ResolutionException('Cannot resolve parameter $' . $parameter->name());
    }
}
