<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\UpdateUserRoles\UpdateUserRolesCommand;
use App\Administration\Application\Command\UpdateUserRoles\UpdateUserRolesHandler;
use App\Administration\Domain\Exception\DernierRoleNonRetirableException;
use App\Administration\Domain\Exception\RoleDejaAttribueException;
use App\Administration\Domain\Exception\RoleNonAttribueException;
use App\Administration\Domain\Exception\UserNotFoundException;
use App\Administration\Domain\Model\User\Role;
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 function in_array;

use InvalidArgumentException;
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 UpdateUserRolesProcessor implements ProcessorInterface
{
    public function __construct(
        private UpdateUserRolesHandler $handler,
        private MessageBusInterface $eventBus,
        private AuthorizationCheckerInterface $authorizationChecker,
        private TenantContext $tenantContext,
        private Clock $clock,
        private Security $security,
    ) {
    }

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

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

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

        /** @var string[] $roles */
        $roles = $data->roles ?? [];

        // Guard: prevent privilege escalation (only SUPER_ADMIN can assign SUPER_ADMIN)
        $currentUser = $this->security->getUser();
        if ($currentUser instanceof SecurityUser) {
            $currentRoles = $currentUser->getRoles();

            if (!in_array(Role::SUPER_ADMIN->value, $currentRoles, true)
                && in_array(Role::SUPER_ADMIN->value, $roles, true)) {
                throw new AccessDeniedHttpException('Seul un super administrateur peut attribuer le rôle SUPER_ADMIN.');
            }

            // Guard: prevent admin self-demotion
            if ($currentUser->userId() === $userId) {
                $isCurrentlyAdmin = in_array(Role::ADMIN->value, $currentRoles, true)
                    || in_array(Role::SUPER_ADMIN->value, $currentRoles, true);
                $willRemainAdmin = in_array(Role::ADMIN->value, $roles, true)
                    || in_array(Role::SUPER_ADMIN->value, $roles, true);

                if ($isCurrentlyAdmin && !$willRemainAdmin) {
                    throw new BadRequestHttpException('Vous ne pouvez pas retirer votre propre rôle administrateur.');
                }
            }
        }

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

            // Domain events are collected by the aggregate during handler execution,
            // then pulled and dispatched here. The handler does not dispatch events —
            // this is the single dispatch point, not a double dispatch.
            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 (InvalidArgumentException|RoleDejaAttribueException|RoleNonAttribueException|DernierRoleNonRetirableException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
    }
}
