<?php

namespace apexl\Io\middleware\twoFactorAuth;

use apexl\Config\Singleton;
use apexl\Io\includes\Hook;
use apexl\Io\includes\Routes;
use apexl\Io\includes\System;
use apexl\Io\modules\user\entities\sessionEntity;
use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\modules\user\services\currentUser;
use apexl\Io\services\globalData;
use apexl\Io\services\Output;
use apexl\Utils\Urls\Host;
use apexl\Vault\Vault;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;

class twoFactorAuthController implements MiddlewareInterface
{
    protected $globalData;
    protected $config;

    public function __construct(globalData $globalData, Singleton $config)
    {
        $this->globalData = $globalData;
        $this->config = $config;
    }

    public function process(Request $request, RequestHandler $handler): Response
    {
        if ($request->getMethod() === 'OPTIONS') { // Ignore for OPTIONS Requests
            return $handler->handle($request);
        }

        $ignorePaths = [
            '/authenticated',
            '/system/globalData',
            '/two-factor-auth'
        ];
        foreach ($ignorePaths as $path) {
            if (strpos($request->getUri()->getPath(), $path) !== false) { // Allow 2FA auth endpoint through
                return $handler->handle($request);
            }
        }

        $sessionEntity = currentUser::getSessionEntity($request);
        if ($sessionEntity instanceof \Exception) {
            Output::addSystemError($sessionEntity, '403');
        } elseif (isset($sessionEntity->uid)) {

            $userEntity = new userEntity();
            $userEntity->load($sessionEntity->uid);
            $sessionData = $sessionEntity->getSessionData();

            if ($userEntity->two_factor_enabled == '1' && (!isset($sessionData->twoFaPassed) || $sessionData->twoFaPassed == '0')) {
                $response = new \Slim\Psr7\Response();


                $output = Output::getInstance();
                $output::addMetadata('twofactor-auth-middleware', 'redirect', Routes::getRoutePattern('user.display.two-factor-auth.authenticate'));

                return System::asJson($response, ['message' => 'Two Factor Authentication Required'], 401);
            }
        }

        return $handler->handle($request);
    }


}
