<?php

declare(strict_types=1);

namespace App\State\Provider\Organization\Subdomain;

use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\ApiResources\Organization\Subdomain\SubdomainAvailability;
use App\Service\File\Exception\FileNotFoundException;
use App\Service\Typo3\SubdomainService;
use Symfony\Component\HttpFoundation\Response;

/**
 * Custom provider permettant de tester la disponibilité d'un sous-domaine.
 */
final class SubdomainAvailabilityProvider implements ProviderInterface
{
    public function __construct(
        private readonly SubdomainService $subdomainService,
    ) {
    }

    /**
     * @param array<mixed> $uriVariables
     * @param array<mixed> $context
     *
     * @throws FileNotFoundException
     */
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): SubdomainAvailability
    {
        if ($operation instanceof GetCollection) {
            throw new \RuntimeException('not supported', Response::HTTP_METHOD_NOT_ALLOWED);
        }

        $filters = $context['filters'] ?? [];
        $subdomain = $filters['subdomain'] ?? null;
        if ($subdomain === null) {
            throw new \RuntimeException('missing parameter: subdomain', Response::HTTP_BAD_REQUEST);
        }

        $available =
            !$this->subdomainService->isRegistered($subdomain)
            && !$this->subdomainService->isReservedSubdomain($subdomain);

        $subdomainAvailability = new SubdomainAvailability();
        $subdomainAvailability->setSubdomain($subdomain);
        $subdomainAvailability->setAvailable($available);

        return $subdomainAvailability;
    }
}
