<?php

namespace NoahVet\Reef\Security\Authentication\Passport\Badge;

use Symfony\Component\Security\Http\Authenticator\Passport\Badge\BadgeInterface;

class TokenExpirationBadge implements BadgeInterface
{
    /**
     * @var callable
     */
    protected $expirationDateLoader;

    protected ?\DateTimeImmutable $expirationDate;

    protected bool $loaded;

    protected string $oauthToken;

    public function __construct(string $oauthToken, callable $expirationDateLoader)
    {
        $this->expirationDateLoader = $expirationDateLoader;
        $this->oauthToken = $oauthToken;
        $this->expirationDate = null;
        $this->loaded = false;
    }

    #[\Override]
    public function isResolved(): bool
    {
        $expirationDate = $this->loadExpirationDate();

        return null !== $expirationDate && $expirationDate->getTimestamp() > \time();
    }

    public function getExpirationDate(): \DateTimeImmutable
    {
        $expirationDate = $this->loadExpirationDate();

        if (null === $expirationDate) {
            throw new \RuntimeException('Token expiration date is not resolved.');
        }

        return $expirationDate;
    }

    protected function loadExpirationDate(): ?\DateTimeImmutable
    {
        if (!$this->loaded) {
            $this->expirationDate = ($this->expirationDateLoader)($this->oauthToken);
        }

        $this->loaded = true;

        return $this->expirationDate;
    }
}
