<?php

declare(strict_types=1);

namespace KupShop\TwoFactorBundle\Security;

use KupShop\UserBundle\Security\User;
use Scheb\TwoFactorBundle\Model\Email\TwoFactorInterface;

class TwoFactorUser extends User implements TwoFactorInterface
{
    private ?string $authCode;

    public function isEmailAuthEnabled(): bool
    {
        $settings = \Settings::getDefault();
        $ignoredGroups = $settings['two_factor']['ignored_groups'] ?? [];

        foreach ($ignoredGroups as $ignoredGroup) {
            if ($this->getKupshopUser()->hasGroupId($ignoredGroup)) {
                return false;
            }
        }

        return findModule(\Modules::TWO_FACTOR) && ($settings['two_factor']['enabled'] ?? false);
    }

    public function getEmailAuthRecipient(): string
    {
        return $this->email;
    }

    public function getEmailAuthCode(): string
    {
        $code = $this->authCode ?? null;

        if (!$code) {
            $code = $this->getKupshopUser()->getCustomData()['email_code'];
            if (!$code) {
                throw new \LogicException('The email authentication code was not set');
            }
        }

        return $code;
    }

    public function setEmailAuthCode(string $authCode): void
    {
        $this->authCode = $authCode;
    }
}
