<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Domain\Model\User\Role;
use App\Administration\Domain\Repository\ActivationTokenRepository;
use App\Administration\Infrastructure\Api\Resource\ActivationTokenInfo;
use App\Shared\Domain\Clock;
use DateTimeImmutable;
use Override;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * API Platform provider for activation token information.
 *
 * @implements ProviderInterface<ActivationTokenInfo>
 */
final readonly class ActivationTokenInfoProvider implements ProviderInterface
{
    public function __construct(
        private ActivationTokenRepository $tokenRepository,
        private Clock $clock,
    ) {
    }

    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): ActivationTokenInfo
    {
        /** @var string $tokenValue */
        $tokenValue = $uriVariables['tokenValue'] ?? '';

        $token = $this->tokenRepository->findByTokenValue($tokenValue);

        if ($token === null) {
            throw new NotFoundHttpException('Token d\'activation introuvable.');
        }

        if ($token->isUsed()) {
            throw new NotFoundHttpException('Ce token d\'activation a déjà été utilisé.');
        }

        return new ActivationTokenInfo(
            tokenValue: $token->tokenValue,
            email: $token->email,
            role: $this->translateRole($token->role),
            schoolName: $token->schoolName,
            isExpired: $token->isExpired($this->clock->now()),
            expiresAt: $token->expiresAt->format(DateTimeImmutable::ATOM),
        );
    }

    private function translateRole(string $role): string
    {
        $roleEnum = Role::tryFrom($role);

        return $roleEnum?->label() ?? $role;
    }
}
