<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\CreateClass\CreateClassCommand;
use App\Administration\Application\Command\CreateClass\CreateClassHandler;
use App\Administration\Domain\Exception\ClasseDejaExistanteException;
use App\Administration\Domain\Exception\ClassNameInvalideException;
use App\Administration\Infrastructure\Api\Resource\ClassResource;
use App\Administration\Infrastructure\Security\ClassVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Ramsey\Uuid\Uuid;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * Processor API Platform pour créer une classe.
 *
 * @implements ProcessorInterface<ClassResource, ClassResource>
 */
final readonly class CreateClassProcessor implements ProcessorInterface
{
    public function __construct(
        private CreateClassHandler $handler,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

    /**
     * @param ClassResource $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): ClassResource
    {
        if (!$this->authorizationChecker->isGranted(ClassVoter::CREATE)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à créer une classe.');
        }

        if (!$this->tenantContext->hasTenant()) {
            throw new UnauthorizedHttpException('Bearer', 'Tenant non défini.');
        }

        $tenantId = (string) $this->tenantContext->getCurrentTenantId();

        // TODO: Récupérer school_id et academic_year_id depuis le contexte utilisateur
        // quand les modules Schools et AcademicYears seront implémentés.
        // Pour l'instant, on utilise des UUIDs déterministes basés sur le tenant.
        $schoolId = Uuid::uuid5(Uuid::NAMESPACE_DNS, "school-{$tenantId}")->toString();
        $academicYearId = Uuid::uuid5(Uuid::NAMESPACE_DNS, "academic-year-2024-2025-{$tenantId}")->toString();

        try {
            $command = new CreateClassCommand(
                tenantId: $tenantId,
                schoolId: $schoolId,
                academicYearId: $academicYearId,
                name: $data->name ?? '',
                level: $data->level,
                capacity: $data->capacity,
            );

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

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

            // Return the created resource
            $resource = new ClassResource();
            $resource->id = (string) $class->id;
            $resource->name = (string) $class->name;
            $resource->level = $class->level?->value;
            $resource->capacity = $class->capacity;
            $resource->status = $class->status->value;

            return $resource;
        } catch (ClassNameInvalideException $e) {
            throw new BadRequestHttpException($e->getMessage());
        } catch (ClasseDejaExistanteException $e) {
            throw new ConflictHttpException($e->getMessage());
        }
    }
}
