<?php

declare(strict_types=1);

namespace apexl\Io\modules\component\Factories;

use apexl\Io\modules\component\Collections\ComponentCollection;
use apexl\Io\modules\component\Collections\ComponentPropertyCollection;
use apexl\Io\modules\component\Interfaces\ComponentInterface;
use Arrayy\Type\StringCollection;
use DI\Container;
use function apexl\Io\assertInstanceOf;

final readonly class GenericComponentFactory
{
    public function __construct(private Container $container) {}

    /**
     * @var class-string<ComponentInterface> $class
     */
    public function make(string $class, array $initParams = [], array $constructorParams = []): ComponentInterface
    {
        assertInstanceOf($class, ComponentInterface::class);

        /** @var ComponentInterface $component */
        $component = $this->container->make($class, [
            'props' => new ComponentPropertyCollection(),
            'components' => new ComponentCollection(),
            'classes' => new StringCollection(),
            ...$constructorParams,
        ]);

        if (is_callable([$component, 'init'])) {
            $component->init(...$initParams);
        }

        return $component;
    }
}