<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\CreateSubject\CreateSubjectCommand;
use App\Administration\Application\Command\CreateSubject\CreateSubjectHandler;
use App\Administration\Domain\Exception\SubjectCodeInvalideException;
use App\Administration\Domain\Exception\SubjectColorInvalideException;
use App\Administration\Domain\Exception\SubjectDejaExistanteException;
use App\Administration\Domain\Exception\SubjectNameInvalideException;
use App\Administration\Infrastructure\Api\Resource\SubjectResource;
use App\Administration\Infrastructure\School\SchoolIdResolver;
use App\Administration\Infrastructure\Security\SubjectVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;
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\UnauthorizedHttpException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * Processor API Platform pour créer une matière.
 *
 * @implements ProcessorInterface<SubjectResource, SubjectResource>
 */
final readonly class CreateSubjectProcessor implements ProcessorInterface
{
    public function __construct(
        private CreateSubjectHandler $handler,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private AuthorizationCheckerInterface $authorizationChecker,
        private SchoolIdResolver $schoolIdResolver,
    ) {
    }

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

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

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

        try {
            $command = new CreateSubjectCommand(
                tenantId: $tenantId,
                schoolId: $schoolId,
                name: $data->name ?? '',
                code: $data->code ?? '',
                color: $data->color,
            );

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

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

            return SubjectResource::fromDomain($subject);
        } catch (SubjectNameInvalideException|SubjectCodeInvalideException|SubjectColorInvalideException $e) {
            throw new BadRequestHttpException($e->getMessage());
        } catch (SubjectDejaExistanteException $e) {
            throw new ConflictHttpException($e->getMessage());
        }
    }
}
