<?php

namespace App\State\Provider\OnlineRegistration;

use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\ApiResources\OnlineRegistration\RegistrationAvailability;
use App\Entity\Access\Access;
use App\Service\ApiLegacy\ApiLegacyRequestService;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class RegistrationAvailabilityProvider implements ProviderInterface
{
    public function __construct(
        private Security $security,
        private ApiLegacyRequestService $apiLegacyRequestService
    ) {}

    /**
     * @param Operation $operation
     * @param mixed[] $uriVariables
     * @param mixed[] $context
     * @return RegistrationAvailability|null
     */
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): ?RegistrationAvailability
    {
        if($operation instanceof GetCollection) {
            throw new \RuntimeException('not supported', 500);
        }

        /** @var Access $currentAccess */
        $currentAccess = $this->security->getUser();
        if ($uriVariables['accessId'] !== $currentAccess->getId()) {
            throw new \RuntimeException('forbidden', 503);
        }

        $response = $this->apiLegacyRequestService->get("/api/online_registration/access_verification");

        $content = json_decode($response->getContent(false), true, 512, JSON_THROW_ON_ERROR);

        $availability = new RegistrationAvailability();
        $availability->setAccessId($currentAccess->getId());
        $availability->setAvailable($response->getStatusCode() === 200);
        $availability->setMessage($content['message']);

        return $availability;
    }
}
