<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\DI\Definition;

use Closure;
use PpPhp\Core\Platform\DI\Contracts\ContainerInterface;
use PpPhp\Core\Platform\DI\Contracts\ResolverInterface;
use PpPhp\Core\Platform\DI\Metadata\DefinitionType;
use PpPhp\Core\Platform\DI\Metadata\Lifetime;

final class FactoryDefinition extends AbstractDefinition
{
    private Closure $factory;

    public function __construct(string $id, callable $factory, string $lifetime = Lifetime::FACTORY)
    {
        parent::__construct($id, $lifetime);
        $this->factory = $factory(...);
    }

    public function type(): string { return DefinitionType::FACTORY_SERVICE; }
    public function factory(): Closure { return $this->factory; }

    public function resolve(ContainerInterface $container, ResolverInterface $resolver): mixed
    {
        return ($this->factory)($container);
    }

    public function toArray(): array
    {
        return $this->baseArray() + ['factory' => 'Closure'];
    }
}
