<?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\RegistrationStatus;
use App\Entity\Access\Access;
use App\Enum\OnlineRegistration\RegistrationStatusEnum;
use App\Service\ApiLegacy\ApiLegacyRequestService;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\Response;

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

    /**
     * @param mixed[] $uriVariables
     * @param mixed[] $context
     *
     * @throws \JsonException
     */
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): ?RegistrationStatus
    {
        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);
        }

        // --- L'appel au service remplacera l'appel à l'API v1 à l'avenir --
        // $registrationStatusValue = $this->registrationStatusService->getStatus($currentAccess);

        $response = $this->apiLegacyRequestService->getJsonContent(
            '/api/online_registration/registration_status',
            [],
            [],
            false
        );

        $statusMap = [
            'your_application_is_awaiting_processing' => RegistrationStatusEnum::NEGOTIABLE,
            'your_registration_file_has_been_validated' => RegistrationStatusEnum::ACCEPTED,
            'you_have_been_placed_on_the_waiting_list' => RegistrationStatusEnum::PENDING,
            'your_application_has_been_refused' => RegistrationStatusEnum::DENIED,
        ];

        $status = $response['status'] ? $statusMap[$response['status']] : null;

        $registrationStatus = new RegistrationStatus();
        $registrationStatus->setAccessId($currentAccess->getId());
        $registrationStatus->setStatus($status);

        return $registrationStatus;
    }
}
