<?php

namespace Trainingssystem\Module\App\Rule;

use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Token\InvalidTokenStructure;

class HasRequestValidJwtRule
{
    private Configuration $jwtConfiguration;

    public function __construct(Configuration $jwtConfiguration)
    {
        $this->jwtConfiguration = $jwtConfiguration;
    }

    public function apply(\WP_REST_Request $request): bool
    {
        $authorizationString = $request->get_header('Authorization');
        if ($authorizationString === null) {
            return false;
        }

        try {
            $token = $this->jwtConfiguration->parser()->parse(substr($authorizationString, 7));
        } catch (InvalidTokenStructure $exception) {
            return false;
        }

        $user = wp_set_current_user($token->claims()->get('uid'));

        if ($user->ID > 0) {
            return true;
        }

        return false;
    }
}
