<?php

declare(strict_types=1);

namespace Apexl\UserTabulator\Hooks;

use apexl\Io\interfaces\AbstractHook;
use apexl\Io\modules\tabulator\Components\Tabulator;
use apexl\Io\modules\user\services\CurrentUserFactory;
use Apexl\UserTabulator\Dto\TabulatorLayoutDto;
use Apexl\UserTabulator\Services\TabulatorUserLayoutKeyService;

final readonly class SetTabulatorColumns implements AbstractHook
{
    public function __construct(
        private CurrentUserFactory $currentUserFactory,
        private TabulatorUserLayoutKeyService $userLayoutKeyService
    ) {}

    public function hooks(): array
    {
        return [Tabulator::HOOK__INIT];
    }

    public function __invoke(Tabulator $tabulator): void
    {
        $userLayout = $this->userLayout($tabulator);

        if ($userLayout) {
            $tabulator->setActiveColumns($userLayout->columns);
        }
    }

    private function userLayout(Tabulator $tabulator): ?TabulatorLayoutDto
    {
        $found = $this->currentUserFactory
            ->get()
            ?->meta($this->userLayoutKeyService->key($tabulator->viewId()))
            ?->meta_value;

        return $found instanceof TabulatorLayoutDto ? $found : null;
    }
}