<?php
declare(strict_types=1);

namespace Celena\Module\Dashboard;

use Celena\Core\Container;
use Celena\Core\Http\Request;
use Celena\Core\Http\Response;
use Celena\Core\Security\Csrf;
use Celena\Core\Template\BlockRegistry;
use Celena\Core\Template\Engine;
use Celena\Module\Settings\Options;

/**
 * GET /api/blocks/{name} — отрисовка async-блока, зарегистрированного через BlockRegistry.
 * Возвращает HTML. CSRF-проверка для POST-вариантов.
 */
final class BlockController
{
    public function __construct(
        private readonly BlockRegistry $registry,
        private readonly Engine $engine,
        private readonly Container $container,
        private readonly Options $options,
    ) {
    }

    public function show(Request $request, array $params): Response
    {
        $name = (string) ($params['name'] ?? '');
        if (!$this->registry->has($name)) {
            return Response::json(['error' => 'block_not_found'], 404);
        }
        if ($request->method !== 'GET' && !Csrf::validate($request->header('x-csrf-token') ?? (string) $request->input('_csrf'))) {
            return Response::json(['error' => 'csrf_invalid'], 403);
        }
        $resolved = $this->registry->resolve($name, $this->container, $request->get + $request->post);
        if ($resolved === null) {
            return Response::notFound();
        }
        $this->engine->setTheme((string) $this->options->get('theme', 'default'));
        $html = $this->engine->render($resolved['template'], $resolved['vars']);
        return Response::html($html);
    }
}
