<?php

declare(strict_types=1);

namespace Apexl\Io\User\Controllers;

use Apexl\Io\Controller;
use Apexl\Io\Exceptions\RecordNotFoundException;
use Apexl\Io\Exceptions\RouteNotFoundException;
use Apexl\Io\Services\RouteUrls;
use Apexl\Io\User\Actions\StartMasqueradeAction;
use Apexl\Io\User\Exceptions\MasqueradeException;
use Apexl\Io\User\Exceptions\SessionException;
use Apexl\Io\User\Requests\MasqueradeRequest;
use app\module\newtonsTrailers\Entity\Contact;
use JsonException;
use Psr\Http\Message\ResponseInterface;

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

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

        try {
            $masqueradeAction->handle($to);
        } catch (MasqueradeException|SessionException $e) {
            \Apexl\Io\Logger\logger()->error($e->getMessage());

            $this->output->addMessage('masquerade.error', 'error', 'Could not start masquerade.');
            $this->output->addRedirect('redirect.masquerade', $routeUrls->url('home'));

            return $this->json($response, [], 401);
        }

        $this->output->addRedirect('redirect.masquerade', $routeUrls->url('home'));


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