<?php

declare(strict_types=1);

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

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

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

    private ?\DateTimeImmutable $expirationDate;

    private bool $loaded;

    private string $oauthToken;

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

    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;
    }

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

        $this->loaded = true;

        return $this->expirationDate;
    }
}
