<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\DeleteLogo\DeleteLogoCommand;
use App\Administration\Application\Command\DeleteLogo\DeleteLogoHandler;
use App\Administration\Domain\Exception\SchoolBrandingNotFoundException;
use App\Administration\Infrastructure\Api\Resource\SchoolBrandingResource;
use App\Administration\Infrastructure\School\SchoolIdResolver;
use App\Administration\Infrastructure\Security\SchoolBrandingVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
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 le logo (DELETE /school/branding/logo).
 *
 * @implements ProcessorInterface<SchoolBrandingResource, null>
 */
final readonly class DeleteLogoProcessor implements ProcessorInterface
{
    public function __construct(
        private DeleteLogoHandler $handler,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private AuthorizationCheckerInterface $authorizationChecker,
        private SchoolIdResolver $schoolIdResolver,
    ) {
    }

    /**
     * @param SchoolBrandingResource $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): null
    {
        if (!$this->authorizationChecker->isGranted(SchoolBrandingVoter::CONFIGURE)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à configurer le branding.');
        }

        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 DeleteLogoCommand(
                tenantId: $tenantId,
                schoolId: $schoolId,
            );

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

            foreach ($branding->pullDomainEvents() as $event) {
                $this->eventBus->dispatch($event);
            }

            return null;
        } catch (SchoolBrandingNotFoundException) {
            throw new NotFoundHttpException('Branding non trouvé pour cet établissement.');
        }
    }
}
