<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\InviteUser\InviteUserCommand;
use App\Administration\Application\Command\InviteUser\InviteUserHandler;
use App\Administration\Domain\Exception\EmailDejaUtiliseeException;
use App\Administration\Domain\Exception\EmailInvalideException;
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\ConflictHttpException;
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 InviteUserProcessor implements ProcessorInterface
{
    public function __construct(
        private InviteUserHandler $handler,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private AuthorizationCheckerInterface $authorizationChecker,
        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::CREATE)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à créer un utilisateur.');
        }

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

        $tenantId = (string) $this->tenantContext->getCurrentTenantId();
        $tenantConfig = $this->tenantContext->getCurrentTenantConfig();

        // Guard: prevent privilege escalation (only SUPER_ADMIN can assign SUPER_ADMIN)
        /** @var string[] $requestedRoles */
        $requestedRoles = $data->roles ?? [];
        $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, $requestedRoles, true)) {
                throw new AccessDeniedHttpException('Seul un super administrateur peut attribuer le rôle SUPER_ADMIN.');
            }
        }

        try {
            $roles = $data->roles ?? [];
            $role = $data->role ?? ($roles[0] ?? '');

            $command = new InviteUserCommand(
                tenantId: $tenantId,
                schoolName: $tenantConfig->subdomain,
                email: $data->email ?? '',
                role: $role,
                firstName: $data->firstName ?? '',
                lastName: $data->lastName ?? '',
                roles: $roles,
                studentId: $data->studentId,
                relationshipType: $data->relationshipType,
            );

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

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

            return UserResource::fromDomain($user, $this->clock->now());
        } catch (EmailInvalideException|InvalidArgumentException $e) {
            throw new BadRequestHttpException($e->getMessage());
        } catch (EmailDejaUtiliseeException $e) {
            throw new ConflictHttpException($e->getMessage());
        }
    }
}
