<?php

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\Repository\Access\AccessRepository;
use App\Service\ApiLegacy\ApiLegacyRequestService;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use RuntimeException;

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

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

        // --- 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");
        if (!isset($response['status'])) {
            throw new RuntimeException('An error occured', 500);
        }

        $statusMap = [
            "your_application_is_awaiting_processing" => RegistrationStatusEnum::NEGOTIABLE()->getValue(),
            "your_registration_file_has_been_validated" => RegistrationStatusEnum::ACCEPTED()->getValue(),
            "you_have_been_placed_on_the_waiting_list" => RegistrationStatusEnum::PENDING()->getValue(),
            "your_application_has_been_refused" => RegistrationStatusEnum::DENIED()->getValue(),
            null => null
        ];

        $status  = $statusMap[$response['status']];

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

        return $registrationStatus;
    }

}
