<?php

declare(strict_types=1);

namespace apexl\Io\modules\tabulator\Controllers;

use apexl\Io\exceptions\LoaderConditionResolutionException;
use apexl\Io\exceptions\TabulatorFilterConditionCannotBeConvertedToWhereException;
use apexl\Io\includes\Controller;
use apexl\Io\interfaces\OutputManagerInterface;
use apexl\Io\modules\tabulator\Interfaces\HasTabulatorViewInterface;
use apexl\Io\modules\tabulator\Request\TabulatorRequest;
use apexl\Io\modules\tabulator\Services\TabulatorDataService;
use JsonException;
use Psr\Http\Message\ResponseInterface;
use function apexl\Io\assertInstanceOf;

final readonly class TabulatorController extends Controller
{
    /**
     * @param class-string<HasTabulatorViewInterface> $entityClass
     */
    public function __construct(
        private string $entityClass,
        private TabulatorDataService $dataService,
        OutputManagerInterface $output,
    ) {
        assertInstanceOf($entityClass, HasTabulatorViewInterface::class);
        parent::__construct($output);
    }

    /**
     * @throws LoaderConditionResolutionException
     * @throws TabulatorFilterConditionCannotBeConvertedToWhereException
     * @throws JsonException
     */
    public function __invoke(
        TabulatorRequest $request,
        ResponseInterface $response,
    ): ResponseInterface {
        $data = $this->dataService->get(
            new $this->entityClass(),
            $request->filters(),
            $request->sort(),
            $request->size(),
            $request->page(),
            $request->subEntityKey(),
        )->toArray();

        return $this->json($response, $data);
    }
}
