<?php

namespace Drupal\miniorange_webauthn\MoService;

class MoPubKeyReqProfileGenFactory
{
  /**
   * todo below can be upgraded to something like Admin configurable
   *  1. security level cna be changed
   *  2. User Verifications can be changed
   */
  private function getContext(): array
  {
    $request = \Drupal::request();

    $user_agent = $request->headers->get('User-Agent');
    $deviceType = str_contains($user_agent, 'Mobile') ? 'mobile' : 'desktop';
    return [
      'security_level' => 'high',
      'device_type' => $deviceType,
    ];
  }

  public function generateRuntimeProfile(array $context = []): array {

    if (empty($context)) {
      $context = $this->getContext();
    }
    $securityLevel = $context['security_level'] ?? 'default';
    $deviceType = $context['device_type'] ?? 'unknown';

    // Basic RP entity setup
    $rp = $this->getRPBasics();

    // Determine challenge length based on security level
    $challengeLength = $this->getChallengeLength($securityLevel);

    // Timeout policy (in milliseconds)
    $timeout = $this->getTimeOut($deviceType);

    // Determine user verification based on user level
    $userVerification = $this->getUserVerification($deviceType);

    // Extensions: Example of adding credProps or custom flags
    $extensions = [
      'uvm' => true
    ];

    return [
      'rp_id' => $rp,
      'challenge_length' => $challengeLength,
      'timeout' => $timeout,
      'user_verification' => $userVerification,
      'extensions' => $extensions,
    ];
  }

  /**
   * @param mixed $securityLevel
   * @return int
   */
  public function getChallengeLength(mixed $securityLevel): int
  {
    return match ($securityLevel) {
      'high' => 64,
      'medium' => 48,
      default => 32,
    };
  }

  /**
   * @param mixed $deviceType
   * @return int
   */
  public function getTimeOut(mixed $deviceType): int
  {
    return match ($deviceType) {
      'mobile' => 90000,
      'desktop' => 60000,
      default => 30000,
    };
  }

  /**
   * @param mixed $deviceType
   * @return string
   */
  public function getUserVerification(mixed $deviceType): string
  {
    return $deviceType === 'mobile' ? 'required' : 'preferred';
  }

  /**
   * @return array
   */
  public function getRPBasics(): string
  {
    return \Drupal::request()->getHost();
  }
}
