<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\UnblockUser\UnblockUserCommand;
use App\Administration\Application\Command\UnblockUser\UnblockUserHandler;
use App\Administration\Domain\Exception\UserNotFoundException;
use App\Administration\Domain\Exception\UtilisateurNonDeblocableException;
use App\Administration\Infrastructure\Api\Resource\UserResource;
use App\Administration\Infrastructure\Security\UserVoter;
use App\Shared\Domain\Clock;
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\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 UnblockUserProcessor implements ProcessorInterface
{
    public function __construct(
        private UnblockUserHandler $handler,
        private MessageBusInterface $eventBus,
        private AuthorizationCheckerInterface $authorizationChecker,
        private TenantContext $tenantContext,
        private Clock $clock,
    ) {
    }

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

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

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

        try {
            $command = new UnblockUserCommand(
                userId: $userId,
                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 (UtilisateurNonDeblocableException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
    }
}
