<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Service\RoleContext;
use App\Administration\Domain\Exception\RoleNonAttribueException;
use App\Administration\Domain\Exception\UserNotFoundException;
use App\Administration\Domain\Model\User\Role;
use App\Administration\Domain\Model\User\UserId;
use App\Administration\Domain\Repository\UserRepository;
use App\Administration\Infrastructure\Api\Resource\SwitchRoleInput;
use App\Administration\Infrastructure\Api\Resource\SwitchRoleOutput;
use App\Administration\Infrastructure\Security\SecurityUser;
use DomainException;
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;

/**
 * @implements ProcessorInterface<SwitchRoleInput, SwitchRoleOutput>
 */
final readonly class SwitchRoleProcessor implements ProcessorInterface
{
    public function __construct(
        private Security $security,
        private UserRepository $userRepository,
        private RoleContext $roleContext,
    ) {
    }

    /**
     * @param SwitchRoleInput $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): SwitchRoleOutput
    {
        $currentUser = $this->security->getUser();
        if (!$currentUser instanceof SecurityUser) {
            throw new UnauthorizedHttpException('Bearer', 'Authentification requise.');
        }

        $role = Role::tryFrom($data->role ?? '');
        if ($role === null) {
            throw new BadRequestHttpException('Rôle invalide.');
        }

        try {
            $user = $this->userRepository->get(UserId::fromString($currentUser->userId()));
            $this->roleContext->switchTo($user, $role);
        } catch (UserNotFoundException $e) {
            throw new NotFoundHttpException($e->getMessage());
        } catch (RoleNonAttribueException $e) {
            throw new BadRequestHttpException($e->getMessage());
        } catch (DomainException $e) {
            throw new AccessDeniedHttpException($e->getMessage());
        }

        return new SwitchRoleOutput(
            activeRole: $role->value,
            activeRoleLabel: $role->label(),
        );
    }
}
