<?php

declare(strict_types=1);

namespace apexl\Io\modules\tabulator\Factories;

use apexl\Io\modules\tabulator\Interfaces\HasTabulatorViewInterface;
use apexl\Io\modules\tabulator\Tabulatable\Tabulatable;
use apexl\Utils\Strings\Camel;
use Arrayy\Type\StringCollection;
use DI\Container;
use DI\DependencyException;
use DI\NotFoundException;
use function apexl\Io\assertInstanceOf;

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

    protected static function newClassBasename(array $entityClass): string
    {
        return Camel::camelCase(array_pop($entityClass), true);
    }

    /**
     * @param HasTabulatorViewInterface|class-string<HasTabulatorViewInterface> $entity
     * @throws DependencyException
     * @throws NotFoundException
     */
    public function make(HasTabulatorViewInterface|string $entity, array|StringCollection $fields = [], bool $excludeAjax = true): Tabulatable
    {
        if (is_string($entity)) {
            assertInstanceOf($entity, HasTabulatorViewInterface::class);

            $entity = new $entity();
        }

        $class = $entity->tabulatableClass();

        $instance = $this->container->make($class, [
            'entity' => $entity,
            'fields' => $fields,
            'excludeAjax' => $excludeAjax,
        ]);

        if (method_exists($instance, 'init')) {
            $instance->init();
        }

        return $instance;
    }
}