<?php

declare(strict_types=1);

namespace Apexl\Io\UserLayout\Controllers;

use Apexl\Io\Controller;
use Apexl\Io\User\Services\CurrentUserFactory;
use Apexl\Io\UserLayout\Interfaces\UserLayoutDtoInterface;
use Apexl\Io\UserLayout\Requests\SaveLayoutRequest;
use JsonException;
use Psr\Http\Message\ResponseInterface;

abstract readonly class AbstractSaveLayoutController extends Controller
{
    /**
     * @throws JsonException
     */
    public function __invoke(
        CurrentUserFactory $currentUserFactory,
        SaveLayoutRequest $request,
        ResponseInterface $response,
    ): ResponseInterface {
        $user = $currentUserFactory->get();

        $viewId = $request->viewId();

        $user->addMeta($this->key($viewId), $this->dto($request));

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

    abstract protected function key(string $viewId): string;

    abstract protected function dto(SaveLayoutRequest $request): UserLayoutDtoInterface;
}
