<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\UpdateClass\UpdateClassCommand;
use App\Administration\Application\Command\UpdateClass\UpdateClassHandler;
use App\Administration\Domain\Exception\ClasseDejaExistanteException;
use App\Administration\Domain\Exception\ClasseNotFoundException;
use App\Administration\Domain\Exception\ClassNameInvalideException;
use App\Administration\Domain\Model\SchoolClass\ClassId;
use App\Administration\Domain\Repository\ClassRepository;
use App\Administration\Infrastructure\Api\Resource\ClassResource;
use App\Administration\Infrastructure\Security\ClassVoter;

use function is_string;

use Override;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * Processor API Platform pour modifier une classe.
 *
 * @implements ProcessorInterface<ClassResource, ClassResource>
 */
final readonly class UpdateClassProcessor implements ProcessorInterface
{
    public function __construct(
        private UpdateClassHandler $handler,
        private ClassRepository $classRepository,
        private MessageBusInterface $eventBus,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

    /**
     * @param ClassResource $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): ClassResource
    {
        $classId = $uriVariables['id'] ?? null;

        if (!is_string($classId)) {
            throw new BadRequestHttpException('ID de classe manquant.');
        }

        // Vérifier les permissions avant toute action
        $class = $this->classRepository->findById(ClassId::fromString($classId));
        if ($class === null) {
            throw new NotFoundHttpException('Classe introuvable.');
        }

        if (!$this->authorizationChecker->isGranted(ClassVoter::EDIT, $class)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à modifier cette classe.');
        }

        try {
            $command = new UpdateClassCommand(
                classId: $classId,
                name: $data->name,
                level: $data->level,
                capacity: $data->capacity,
                description: $data->description,
                clearLevel: $data->clearLevel ?? false,
                clearCapacity: $data->clearCapacity ?? false,
                clearDescription: $data->clearDescription ?? false,
            );

            $updatedClass = ($this->handler)($command);

            // Dispatch domain events from the mutated aggregate
            foreach ($updatedClass->pullDomainEvents() as $event) {
                $this->eventBus->dispatch($event);
            }

            // Return updated resource
            $resource = new ClassResource();
            $resource->id = (string) $updatedClass->id;
            $resource->name = (string) $updatedClass->name;
            $resource->level = $updatedClass->level?->value;
            $resource->capacity = $updatedClass->capacity;
            $resource->description = $updatedClass->description;
            $resource->status = $updatedClass->status->value;
            $resource->createdAt = $updatedClass->createdAt;
            $resource->updatedAt = $updatedClass->updatedAt;

            return $resource;
        } catch (ClasseNotFoundException) {
            throw new NotFoundHttpException('Classe introuvable.');
        } catch (ClassNameInvalideException $e) {
            throw new BadRequestHttpException($e->getMessage());
        } catch (ClasseDejaExistanteException $e) {
            throw new ConflictHttpException($e->getMessage());
        }
    }
}
