<?php

namespace Drupal\miniorange_webauthn\MoRepo;

use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\user\Entity\User;
use ParagonIE\ConstantTime\Base64UrlSafe;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Webauthn\PublicKeyCredentialUserEntity;

class MoPubKeyCredUserRepo implements MoPubKeyCredUserRepoInterface
{
  private LoggerInterface $logger;
  public function __construct() {
    $this->logger = new NullLogger();
  }

  /**
   * @throws InvalidPluginDefinitionException
   * @throws PluginNotFoundException
   */
  public function findOneById(?int $id): ?PublicKeyCredentialUserEntity
  {
    if ($id === null) {
      return null;
    }
    /** @var User $user */
    $user = \Drupal::entityTypeManager()->getStorage('user')->load($id);
    if (empty($user)) {
      $this->logger->warning('User with id "{id}" not found', ['id' => $id]);
      return null;
    }
    $encoded_id = Base64UrlSafe::encode($user->id());

    return PublicKeyCredentialUserEntity::create($user->getAccountName(), $encoded_id, $user->getDisplayName());
  }

  public function findOneByUsername(string $username): ?PublicKeyCredentialUserEntity
  {
    $user = current(
      \Drupal::entityTypeManager()->getStorage('user')->loadByProperties(['name' => $username])
    );
    if (empty($user)) {
      $this->logger->warning('User with id "{name}" not found', ['name' => $username]);
      return null;
    }
    $encoded_id = Base64UrlSafe::encode($user->id());

    return PublicKeyCredentialUserEntity::create($user->getAccountName(), $encoded_id, $user->getDisplayName());
  }
}
