<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\DI\Compiler\Factory;

use PpPhp\Core\Platform\DI\Contracts\ContainerInterface;

final class FactoryRegistry
{
    private array $factories = [];

    public function register(string $serviceId, string $factoryClass): void
    {
        $this->factories[$serviceId] = $factoryClass;
    }

    public function has(string $serviceId): bool
    {
        return isset($this->factories[$serviceId]);
    }

    public function create(string $serviceId, ContainerInterface $container): mixed
    {
        $factoryClass = $this->factories[$serviceId] ?? null;

        if (!$factoryClass || !class_exists($factoryClass)) {
            return null;
        }

        $factory = new $factoryClass();

        if (!$factory instanceof CompiledFactoryInterface) {
            return null;
        }

        return $factory->create($container);
    }

    public function all(): array
    {
        return $this->factories;
    }
}
