<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\Actions;

use apexl\Io\includes\HookManager;
use apexl\Io\modules\user\entities\sessionEntity;
use DateTimeImmutable;

final readonly class LogoutAction
{
    public final const string HOOK__LOGOUT_BEFORE = 'logout.before';
    public final const string HOOK__LOGOUT_AFTER = 'logout.after';

    public function __construct(private HookManager $hookManager) {}


    public function handle(object $token): void
    {
        $session = sessionEntity::fromPrimaryKey($token->sessionId);;
        if ($session->sessionId !== null) {
            $this->hookManager->processHook(self::HOOK__LOGOUT_BEFORE, $session->uid);
            $session->active = false;
            $session->ended = new DateTimeImmutable();
            $session->store();
            $this->hookManager->processHook(self::HOOK__LOGOUT_AFTER);
        }
    }
}