<?php

declare(strict_types=1);

namespace apexl\Io\modules\tabulator\Factories;

use apexl\Io\modules\tabulator\Controllers\TabulatorDisplayController;
use apexl\Io\modules\tabulator\Interfaces\HasTabulatorViewInterface;
use apexl\Io\services\EntitySpecificClassNameService;
use DI\Container;
use DI\DependencyException;
use DI\NotFoundException;
use function apexl\Io\assertInstanceOf;

final readonly class TabulatorDisplayControllerFactory
{
    public function __construct(private Container $container, private EntitySpecificClassNameService $classNameService) {}

    /**
     * @param class-string<HasTabulatorViewInterface> $entity
     * @return TabulatorDisplayController
     * @throws DependencyException
     * @throws NotFoundException
     */
    public function make(string $entity): TabulatorDisplayController
    {
        assertInstanceOf($entity, HasTabulatorViewInterface::class);

        $class = $this->getClass($entity);

        return $this->container->make(class_exists($class) ? $class : TabulatorDisplayController::class, [
            'entity' => $entity,
        ]);
    }

    private function getClass(string $entity): string
    {
        /** @var class-string<HasTabulatorViewInterface> $entity */
        $class = $entity::tabulatorDisplayControllerClass();
        if ($class) {
            return $class;
        }
        return $this->classNameService->class(TabulatorDisplayController::class, $entity);
    }
}
