<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\Actions;

use apexl\Io\modules\user\exceptions\MasqueradeException;
use apexl\Io\modules\user\exceptions\SessionException;
use apexl\Io\modules\user\interfaces\CanBeMasqueradedInterface;
use apexl\Io\modules\user\services\CurrentUserFactory;
use apexl\Io\modules\user\services\SessionMasqueradeService;

final readonly class StartMasqueradeAction
{
    public function __construct(
        private CurrentUserFactory $currentUserFactory,
        private SessionMasqueradeService $masqueradeService
    ) {}

    /**
     * @throws MasqueradeException
     * @throws SessionException
     */
    public function handle(CanBeMasqueradedInterface $to): void
    {
        $currentUser = $this->currentUserFactory->get();

        if (!$currentUser) {
            throw new MasqueradeException('Could not get current user.');
        }

        if (!$currentUser->canMasqueradeAs($to)) {
            throw new MasqueradeException('You do not have permission to masquerade as this user.');
        }

        $this->masqueradeService->startMasquerade($to);
    }
}