<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\controllers;

use apexl\Io\exceptions\RecordNotFoundException;
use apexl\Io\includes\Controller;
use apexl\Io\includes\RouteManager;
use apexl\Io\modules\user\Actions\StartMasqueradeAction;
use apexl\Io\modules\user\exceptions\MasqueradeException;
use apexl\Io\modules\user\Request\MasqueradeRequest;
use app\module\newtonsTrailers\Entity\Contact;
use JsonException;
use Psr\Http\Message\ResponseInterface;

final readonly class StartMasqueradeController extends Controller
{
    /**
     * @throws MasqueradeException
     * @throws RecordNotFoundException
     * @throws JsonException
     */
    public function __invoke(
        StartMasqueradeAction $masqueradeAction,
        MasqueradeRequest $request,
        ResponseInterface $response,
        RouteManager $routeManager,
        int $id,
    ): ResponseInterface {
        $to = Contact::find($id, ['user.*'])?->user;

        if ($to === null) {
            throw new RecordNotFoundException();
        }

        $masqueradeAction->handle($to);

        $this->output->addRedirect('redirect.masquerade', $routeManager->getRoutePattern('home'));

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