<?php

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(
        protected readonly JWTDecoderInterface $JWTDecoder,
    ) {
    }

    /**
     * @throws NotJWTException
     * @throws OAuthRequestException
     */
    #[\Override]
    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,
        );
    }

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

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

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

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