<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\services;

use apexl\Io\interfaces\GlobalDataInterface;
use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\modules\user\exceptions\MasqueradeException;
use apexl\Io\modules\user\exceptions\PermissionException;
use apexl\Io\modules\user\interfaces\MasqueradeServiceInterface;

final readonly class CurrentUserFactory
{
    public function __construct(
        private GlobalDataInterface $globalData,
        private MasqueradeServiceInterface $masqueradeService,
    ) {}

    /**
     * @throws MasqueradeException
     */
    public function get(): ?userEntity
    {
        $currentUser = $this->getWithoutMasquerade();

        if (!$currentUser) {
            return null;
        }

        if ($this->masqueradeService->isMasquerading()) {
            $masqueraded = $this->masqueradeService->getMasqueraded();
            try {
                if ($currentUser->canMasqueradeAs($masqueraded)) {
                    return $masqueraded;
                }
            } catch (PermissionException $e) {
                throw new MasqueradeException($e->getMessage(), $e->getCode(), $e);
            }

            throw new MasqueradeException('You do not have permission to masquerade as this user.');
        }

        return $currentUser;
    }

    public function getWithoutMasquerade(): ?userEntity
    {
        return $this->globalData->getData('entities')['user']['entity'] ?? null;
    }

}
