<?php

declare(strict_types=1);

namespace App\Administration\Application\Service;

use App\Administration\Application\Port\ActiveRoleStore;
use App\Administration\Domain\Exception\RoleNonAttribueException;
use App\Administration\Domain\Model\User\Role;
use App\Administration\Domain\Model\User\User;
use DomainException;

final class RoleContext
{
    public function __construct(
        private readonly ActiveRoleStore $activeRoleStore,
    ) {
    }

    public function switchTo(User $user, Role $role): void
    {
        if (!$user->peutSeConnecter()) {
            throw new DomainException('Le compte n\'est pas actif.');
        }

        if (!$user->aLeRole($role)) {
            throw RoleNonAttribueException::pour($user->id, $role);
        }

        $this->activeRoleStore->store($user, $role);
    }

    public function getActiveRole(User $user): Role
    {
        $stored = $this->activeRoleStore->get($user);

        if ($stored !== null) {
            return $stored;
        }

        return $user->rolePrincipal();
    }

    public function clear(User $user): void
    {
        $this->activeRoleStore->clear($user);
    }
}
