<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\UpdateSubject\UpdateSubjectCommand;
use App\Administration\Application\Command\UpdateSubject\UpdateSubjectHandler;
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\Domain\Exception\SubjectNotFoundException;
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 Ramsey\Uuid\Exception\InvalidUuidStringException;
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\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * Processor API Platform pour modifier une matière.
 *
 * @implements ProcessorInterface<SubjectResource, SubjectResource>
 */
final readonly class UpdateSubjectProcessor implements ProcessorInterface
{
    public function __construct(
        private UpdateSubjectHandler $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::EDIT)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à modifier cette matière.');
        }

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

        /** @var string|null $subjectId */
        $subjectId = $uriVariables['id'] ?? null;
        if ($subjectId === null) {
            throw new NotFoundHttpException('Matière non trouvée.');
        }

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

        try {
            $command = new UpdateSubjectCommand(
                subjectId: $subjectId,
                tenantId: $tenantId,
                schoolId: $schoolId,
                name: $data->name,
                code: $data->code,
                color: $data->color,
                description: $data->description,
                clearColor: $data->clearColor ?? false,
                clearDescription: $data->clearDescription ?? false,
            );

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

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

            return SubjectResource::fromDomain($subject);
        } catch (SubjectNotFoundException|InvalidUuidStringException) {
            throw new NotFoundHttpException('Matière non trouvée.');
        } catch (SubjectNameInvalideException|SubjectCodeInvalideException|SubjectColorInvalideException $e) {
            throw new BadRequestHttpException($e->getMessage());
        } catch (SubjectDejaExistanteException $e) {
            throw new ConflictHttpException($e->getMessage());
        }
    }
}
