<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\Actions;

use apexl\Io\modules\user\entities\sessionEntity;
use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\modules\user\Factories\RefreshTokenFactory;
use apexl\Io\modules\user\services\JwtCreator;

final readonly class StartLoggedInSession
{
    public function __construct(
        private JwtCreator $jwtCreator,
        private RefreshTokenFactory $refreshTokenCreator
    ) {}

    public function handle(userEntity $user): array
    {
        $sessionId = $this->randomHexString();
        $token = $this->jwtCreator->forUser(
            $user,
            $sessionId,
        );

        $this->createSession($user->id, $sessionId);
        $this->updateUser($user);

        $refreshToken = $this->refreshTokenCreator->create($user->id);

        return [$token, $refreshToken];
    }

    private function randomHexString(): string
    {
        return bin2hex(random_bytes(20));
    }

    private function createSession(int $userId, string $sessionId): void
    {
        $session = new sessionEntity();
        $session->uid = $userId;
        $session->sessionId = $sessionId;
        $session->created = time();
        $session->ended = 0;
        $session->active = 1;
        $session->store();
    }

    private function updateUser(userEntity $user): void
    {
        $user->last_login = time();
        $user->store();
    }

}