<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\BlockUser\BlockUserCommand;
use App\Administration\Application\Command\BlockUser\BlockUserHandler;
use App\Administration\Domain\Exception\UserNotFoundException;
use App\Administration\Domain\Exception\UtilisateurNonBlocableException;
use App\Administration\Infrastructure\Api\Resource\UserResource;
use App\Administration\Infrastructure\Security\SecurityUser;
use App\Administration\Infrastructure\Security\UserVoter;
use App\Shared\Domain\Clock;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * @implements ProcessorInterface<UserResource, UserResource>
 */
final readonly class BlockUserProcessor implements ProcessorInterface
{
    public function __construct(
        private BlockUserHandler $handler,
        private MessageBusInterface $eventBus,
        private AuthorizationCheckerInterface $authorizationChecker,
        private TenantContext $tenantContext,
        private Security $security,
        private Clock $clock,
    ) {
    }

    /**
     * @param UserResource $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): UserResource
    {
        if (!$this->authorizationChecker->isGranted(UserVoter::BLOCK)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à bloquer un utilisateur.');
        }

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

        /** @var string $userId */
        $userId = $uriVariables['id'] ?? '';

        $currentUser = $this->security->getUser();
        if ($currentUser instanceof SecurityUser && $currentUser->userId() === $userId) {
            throw new BadRequestHttpException('Vous ne pouvez pas bloquer votre propre compte.');
        }

        $reason = trim($data->reason ?? '');
        if ($reason === '') {
            throw new BadRequestHttpException('La raison du blocage est obligatoire.');
        }

        try {
            $command = new BlockUserCommand(
                userId: $userId,
                reason: $reason,
                tenantId: (string) $this->tenantContext->getCurrentTenantId(),
            );
            $user = ($this->handler)($command);

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

            return UserResource::fromDomain($user, $this->clock->now());
        } catch (UserNotFoundException $e) {
            throw new NotFoundHttpException($e->getMessage());
        } catch (UtilisateurNonBlocableException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
    }
}
