<?php
declare(strict_types=1);

namespace App\State\Processor\Organization;

use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put;
use ApiPlatform\State\ProcessorInterface;
use App\Entity\Organization\Subdomain;
use App\Repository\Organization\SubdomainRepository;
use App\Service\Typo3\SubdomainService;
use Doctrine\ORM\EntityManagerInterface;

/**
 * Custom Processor gérant la resource Subdomain
 */
class SubdomainProcessor implements ProcessorInterface
{
    public function __construct(
        private readonly SubdomainService $subdomainService
    ) {}

    /**
     * Persiste l'entité et déclenche les différents hooks de la classe OnChangeInterface définie par le data persister
     *
     * @param Subdomain $data
     * @param Operation $operation
     * @param array<mixed> $uriVariables
     * @param array<mixed> $context
     * @return object
     */
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []) {
        if($operation instanceof Delete){
            throw new \RuntimeException('not supported', 500);
        }

        if ($operation instanceof Post) {
            // Create a new subdomain
            $subdomain = $this->subdomainService->addNewSubdomain(
                $data->getOrganization(),
                $data->getSubdomain(),
                $data->isActive()
            );
        } else if ($operation instanceof Put && $data->isActive()) {
            // Activate a subdomain
            $data->setActive(false); // On triche : c'est le service qui va activer ce sous-domaine, pas le processor
            $subdomain = $this->subdomainService->activateSubdomain($data);
        } else {
            throw new \RuntimeException('not supported', 500);
        }

        return $subdomain;
    }
}
