<?php

namespace apexl\Io\modules\user\controllers;

use apexl\Io\includes\Controller;
use apexl\Io\modules\user\entities\sessionEntity;
use apexl\Io\modules\user\services\currentUser;
use DateTimeImmutable;
use Exception;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final readonly class LogoutController extends Controller
{
    /**
     * @throws Exception
     */
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        [$token] = currentUser::authenticateJWT(
            $request,
            config('auth.jwt.secret_key'),
            config('auth.jwt.algorithm'),
        );

        if ($token) {
            $session = new sessionEntity();
            $session->load($token->sessionId);
            if ($session->sessionId !== null) {
                $session->active = false;
                $session->ended = new DateTimeImmutable();
                $session->store();
            }

            $this->output->addResponse($request); //added so we can hook into this elsewhere.

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

        $this->output->addMessage('user.logout.validation', 'error', 'The user is not logged in');
        $this->output->addResponse($request, [], false); //added so we can hook into this elsewhere.

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