<?php

namespace Drupal\miniorange_webauthn\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\TempStore\PrivateTempStoreFactory;
use Drupal\miniorange_webauthn\MoCredOptBuilder\MoProfileBasedReqOptBuilderInterface;
use Drupal\miniorange_webauthn\MoCredOptBuilder\MoPubKeyCredCreateOptBuildInterface;
use Drupal\miniorange_webauthn\MoProtector\MoHandler\MoFailureHandlerInterface;
use Drupal\miniorange_webauthn\MoProtector\MoPredictor\MoUserPredictorInterface;
use Drupal\miniorange_webauthn\MoProtector\MoStorage\MoItem;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
//use Webauthn\Bundle\CredentialOptionsBuilder\PublicKeyCredentialRequestOptionsBuilder;
//use Webauthn\Bundle\Security\Handler\FailureHandler;
//use Webauthn\Bundle\Security\Handler\RequestOptionsHandler;
//use Webauthn\Bundle\Security\Storage\OptionsStorage;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Throwable;

class MoAssertionReqController extends ControllerBase {

    public function __construct(
        private MoProfileBasedReqOptBuilderInterface $optionsBuilder,
        private readonly PrivateTempStoreFactory $tempStore,
        private readonly MoFailureHandlerInterface $moFailureHandler
    ) {
    }

    public static function create(ContainerInterface $container)
    {
        return new static(
            $container->get('mo_webauthn.profile_based_req_opt_builder'),
            $container->get('tempstore.private'),
            $container->get('mo_webauthn.failure_handler')
        );
    }

    public function __invoke(Request $request) {
        try {
            [$publicKeyCredentialRequestOptions, $userEntity] = $this->optionsBuilder->getFromRequest($request);
            $tempStore = $this->tempStore->get('miniorange_webauthn');
            $tempStore->set('mo_webauthn_assertion_req_opt', MoItem::create($publicKeyCredentialRequestOptions, $userEntity));

            return new JsonResponse($publicKeyCredentialRequestOptions);
        }  catch (Throwable $throwable) {
            return $this->moFailureHandler->onAuthenticationFailure($request, $throwable);
        }

    }
}
