<?php

declare(strict_types=1);

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\Component\HttpFoundation\Response;

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

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

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

        $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() === Response::HTTP_OK && !array_key_exists('error', $content));
        $availability->setMessage(array_key_exists('message', $content) ? $content['message'] : null);

        return $availability;
    }
}
