<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\services;

use apexl\Io\exceptions\RecordNotFoundException;
use apexl\Io\modules\user\entities\RefreshToken;
use apexl\Io\modules\user\exceptions\RefreshTokenExpiredException;
use apexl\Io\modules\user\interfaces\TokenHasherInterface;

final readonly class RefreshTokenEntityFinder
{
    public function __construct(private TokenHasherInterface $tokenHasher) {}

    /**
     * @throws RecordNotFoundException
     * @throws RefreshTokenExpiredException
     */
    public function fromToken(string $token): RefreshToken
    {
        $refreshTokenEntity = RefreshToken::from(
            'token',
            $this->tokenHasher->hash($token)
        );

        if ($refreshTokenEntity->isExpired()) {
            throw new RefreshTokenExpiredException('Token expired');
        }

        return $refreshTokenEntity;
    }
}