<?php

namespace App\Helpers\Lti;
use App\Models\Nonce;
use App\Models\Platform;
use \Firebase\JWT\JWT;
use App\Helpers\Lti\LtiContent;
use Illuminate\Support\Facades\Log;
use App\Http\Requests\LtiLoginInitiation;

class Lti {
    private string $raw_jwt;
    private LtiContent $content;
    private Platform $platform;

    function __construct(string $jwt, string $nonce) {
        Log::debug('[Lti::class] Start Lti class construct');
        $this->raw_jwt = $jwt;
        $nonce = Nonce::where(['value' => $nonce])->firstOrFail();
        $this->platform = $nonce->platform()->firstOrFail();
        $this->content = $this->getContentFromToken();
        LtiTokenValidator::assertTokenNotExpired($this->content);
        LtiTokenValidator::assertLti1p3($this->content);
        LtiTokenValidator::assertValidJwt($this->content, $this->platform);
        $nonce->delete();
        Log::debug('[Lti::class] Lti class constructed correctly');
    }

    public function getPlatform() : Platform {
        return $this->platform;
    }

    public function getContent() : LtiContent {
        return $this->content;
    }

    public function getRawJwtContent() : string {
        return $this->raw_jwt;
    }

    private function getContentFromToken() : object {
        $jwk = $this->platform->getPublicJwk();
        $signature_method = $this->platform->signature_method;
        $raw_content = JWT::decode($this->raw_jwt, $jwk, array($signature_method));
        $content = new LtiContent($raw_content);
        Log::debug('[Lti::class] Jwt decoded successfully');
        return $content;
    }

    public static function isLoginHint(LtiLoginInitiation $request) : bool {
        return isset($request->login_hint);
    }

    public static function isLtiToken(LtiLoginInitiation $request) : bool {
        return isset($request->id_token);
    }

}
