<?php

namespace apexl\Io\modules\user\services\twoFactorAuth\methods;

use apexl\Config\Singleton;
use apexl\Io\modules\user\entities\twoFactorMethodEntity;
use apexl\Io\modules\user\services\currentUser;
use apexl\Io\modules\user\services\twoFactorAuth\TwoFactorAuthService;
use Psr\Http\Message\ServerRequestInterface as Request;

abstract class Abstract2FaMethod
{
    private $methodName;
    protected $config;
    protected $currentUser;
    protected $twoFactorAuthService;

    abstract public static function getMethodName();
    abstract public function authenticate();
    abstract public function processAuthentication(Request $request, $providedCode);
    abstract public function setup();
    abstract public function processSetup($providedCode);
    
    public function __construct()
    {
        $this->config = Singleton::getInstance();
        $this->currentUser = currentUser::getCurrentUser();
        $this->twoFactorAuthService = new TwoFactorAuthService();
    }
    
    public function isEnabled(): bool
    {
        $methods = $this->config->app->twoFactorAuth->methods ?? [];
        return in_array($this->methodName, $methods);
    }

    public function enable()
    {
        return $this->twoFactorAuthService->enable2Fa();
    }

    protected function processFailedAttempt(twoFactorMethodEntity $twoFactorMethodEntity)
    {
        $twoFactorMethodEntity->failed_attempts = $twoFactorMethodEntity->failed_attempts + 1;
        if ($twoFactorMethodEntity->failed_attempts >= 10) {
            $lockout = new \DateTime('now');
            $lockout->add(new \DateInterval('PT15M'));
            $twoFactorMethodEntity->locked_until = $lockout->format('Y-m-d H:i:s');
            $twoFactorMethodEntity->failed_attempts = 0;
        }
        $twoFactorMethodEntity->store();
    }

}