<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\Actions;

use apexl\Config\Exceptions\MissingConfigException;
use apexl\Io\exceptions\RecordNotFoundException;
use apexl\Io\modules\user\entities\RefreshToken;
use apexl\Io\modules\user\exceptions\RefreshTokenExpiredException;
use apexl\Io\modules\user\services\JwtCreator;
use apexl\Io\modules\user\services\RefreshTokenEntityFinder;
use DI\DependencyException;
use DI\NotFoundException;

final readonly class RefreshAction
{
    public function __construct(
        private JwtCreator $jwtCreator,
        private RefreshTokenEntityFinder $refreshTokenFinder,
    ) {}

    /**
     * @throws RecordNotFoundException
     * @throws RefreshTokenExpiredException
     * @throws DependencyException
     * @throws NotFoundException
     * @throws MissingConfigException
     */
    public function handle(string $token, string $sessionId): string
    {
        $refreshTokenEntity = $this->refreshTokenFinder->fromToken($token);

        // Refresh token still valid?
        $user = $refreshTokenEntity->user();

        $authToken = $this->jwtCreator->forUser(
            $user,
            $sessionId,
        );
        $refreshTokenEntity->expiry = RefreshToken::newExpiryFrom();
        $refreshTokenEntity->store();

        return $authToken;
    }
}