<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\ArchiveSubject\ArchiveSubjectCommand;
use App\Administration\Application\Command\ArchiveSubject\ArchiveSubjectHandler;
use App\Administration\Domain\Exception\SubjectNotFoundException;
use App\Administration\Infrastructure\Api\Resource\SubjectResource;
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\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * Processor API Platform pour supprimer (archiver) une matière.
 *
 * Note: Cette implémentation fait un soft delete (archivage).
 * La vérification des notes associées (T6) sera ajoutée ultérieurement
 * quand le module Notes sera implémenté.
 *
 * @implements ProcessorInterface<SubjectResource, null>
 */
final readonly class DeleteSubjectProcessor implements ProcessorInterface
{
    public function __construct(
        private ArchiveSubjectHandler $handler,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

    /**
     * @param SubjectResource $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): null
    {
        if (!$this->authorizationChecker->isGranted(SubjectVoter::DELETE)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à supprimer 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();

        try {
            // TODO: Vérifier si des notes sont associées (T6)
            // et retourner un warning si c'est le cas (via query param ?confirm=true)

            $command = new ArchiveSubjectCommand(
                subjectId: $subjectId,
                tenantId: $tenantId,
            );

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

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

            return null;
        } catch (SubjectNotFoundException|InvalidUuidStringException) {
            throw new NotFoundHttpException('Matière non trouvée.');
        }
    }
}
