<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Application\Service\RoleContext;
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\MyRolesOutput;
use App\Administration\Infrastructure\Security\SecurityUser;
use App\SuperAdmin\Infrastructure\Security\SecuritySuperAdmin;

use function array_map;

use Override;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

/**
 * @implements ProviderInterface<MyRolesOutput>
 */
final readonly class MyRolesProvider implements ProviderInterface
{
    public function __construct(
        private Security $security,
        private UserRepository $userRepository,
        private RoleContext $roleContext,
    ) {
    }

    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): MyRolesOutput
    {
        $currentUser = $this->security->getUser();

        if ($currentUser instanceof SecuritySuperAdmin) {
            $output = new MyRolesOutput();
            $output->roles = [['value' => 'ROLE_SUPER_ADMIN', 'label' => 'Super Admin']];
            $output->activeRole = 'ROLE_SUPER_ADMIN';
            $output->activeRoleLabel = 'Super Admin';

            return $output;
        }

        if (!$currentUser instanceof SecurityUser) {
            throw new UnauthorizedHttpException('Bearer', 'Authentification requise.');
        }

        try {
            $user = $this->userRepository->get(UserId::fromString($currentUser->userId()));
        } catch (UserNotFoundException $e) {
            throw new NotFoundHttpException($e->getMessage());
        }

        $activeRole = $this->roleContext->getActiveRole($user);

        $output = new MyRolesOutput();
        $output->roles = array_map(
            static fn (Role $role) => ['value' => $role->value, 'label' => $role->label()],
            $user->roles,
        );
        $output->activeRole = $activeRole->value;
        $output->activeRoleLabel = $activeRole->label();

        return $output;
    }
}
