<?php

namespace apexl\Io\modules\user\controllers;

use apexl\Io\includes\Controller;
use apexl\Io\includes\HookManager;
use apexl\Io\includes\RouteManager;
use apexl\Io\modules\user\Actions\LogoutAction;
use apexl\Io\modules\user\exceptions\JwtException;
use apexl\Io\modules\user\Factories\JwtFromRequestServiceFactory;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use function apexl\Io\config;

final readonly class LogoutController extends Controller
{
    public final const string HOOK__LOGOUT_REDIRECT = 'logoutController.logoutRedirect';

    public function __invoke(
        HookManager $hookManager,
        RouteManager $routeManager,
        JwtFromRequestServiceFactory $jwtServiceFactory,
        LogoutAction $action,
        ServerRequestInterface $request,
        ResponseInterface $response
    ): ResponseInterface {
        try {
            $token = $jwtServiceFactory->make($request)->token();

            $action->handle($token);

            $this->output->addMessage('logged_out', 'success', config('auth.login_messages.logged_out'));

            $redirect = $hookManager->processHook(self::HOOK__LOGOUT_REDIRECT, $routeManager->getRoutePattern('user.display.login'));
            $this->output->addRedirect(
                'redirect.logout',
                $redirect
            );

            return $this->json($response);
        } catch (JwtException $exception) {
            $this->output->addMessage(
                'user.logout.validation',
                'error',
                (config('app.environment') === 'production') ? 'Could not log out' : $exception->getMessage(),
            );

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