<?php

namespace apexl\Io\modules\display\controllers;

use apexl\Io\includes\Controller;
use apexl\Io\includes\RouteManager;
use apexl\Io\interfaces\OutputManagerInterface;
use apexl\Io\modules\display\includes\Forms;
use apexl\Io\services\Output;
use JsonException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final readonly class EntityDeleteFormController extends Controller
{
    public function __construct(private RouteManager $routeManager, OutputManagerInterface $output)
    {
        parent::__construct($output);
    }

    /**
     * @throws JsonException
     */
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, string $entity, int $id): ResponseInterface
    {
        // this is a dynamic form so get the entity details from the URL.
        $form = Forms::entityActionButtonForm(
            $this->routeManager->getRoutePattern(
                $entity . '.delete',
                [
                    'id' => $id
                ]
            )
        );
        $form->setMethod('delete');
        $this->output->addResponse($request, $form->getBuiltFormArray());

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