<?php

declare(strict_types=1);

namespace NoahVet\Reef\Security\User\Provider;

use NoahVet\Reef\Exception\NotJWTException;
use NoahVet\Reef\Exception\OAuthRequestException;
use NoahVet\Reef\Security\Token\JWTDecoderInterface;
use NoahVet\Reef\Security\User\ReefOAuthUser;

class JWTReefOAuthUserProvider implements ReefOAuthUserProviderInterface
{
    public function __construct(
        private readonly JWTDecoderInterface $JWTDecoder,
    ) {
    }

    /**
     * @throws NotJWTException
     * @throws OAuthRequestException
     */
    public function loadUser(string $bearerToken): ?ReefOAuthUser
    {
        $token = $this->JWTDecoder->decodeJWT($bearerToken);

        if (null === $token) {
            return null;
        }

        return new ReefOAuthUser(
            (string) $token->sub,
            $token->email ?? null,
        );
    }

    public function getTokenExpiresAt(string $bearerToken): ?\DateTimeImmutable
    {
        $token = $this->JWTDecoder->decodeJWT($bearerToken);

        if (null === $token) {
            return null;
        }

        $exp = (int) $token->exp;

        return new \DateTimeImmutable('@'.$exp);
    }
}
