<?php

namespace apexl\Io\modules\user\controllers;

use apexl\Io\includes\Controller;
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;

final readonly class LogoutController extends Controller
{
    public function __invoke(RouteManager $routeManager, JwtFromRequestServiceFactory $jwtServiceFactory, LogoutAction $action, ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        try {
            $token = $jwtServiceFactory->make($request)->token();

            $action->handle($token);

            $this->output->addRedirect(
                'redirect.logout',
                $routeManager->getRoutePattern('user.display.login', [
                    'loginMessageType' => 'logged_out',
                ])
            );

            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);
        }
    }
}
