<?php

namespace Drupal\miniorange_webauthn\MoRepository;

use Drupal\miniorange_webauthn\Entity\MoWebauthnCredential;
use Webauthn\PublicKeyCredentialSource;
use Webauthn\PublicKeyCredentialUserEntity;

/**
 * WebAuthn PublicKeyCredentialSourceRepository.
 */
final class MoPublicKeyCredentialSourceRepository {

  public function findOneByCredentialId(string $public_key_credential_id): ?PublicKeyCredentialSource {
    $webauthn_credential = MoWebauthnCredential::findOneBy([MoWebauthnCredential::CREDENTIAL_ID => base64_encode($public_key_credential_id)]);
    return $this->generatePublicKeyCredentialSource($webauthn_credential);
  }

  /**
   * {@inheritdoc}
   */
  public function findAllForUserEntity(PublicKeyCredentialUserEntity $public_key_credential_user_entity): array {
    $credential_sources = [];
    $webauthn_credentials = MoWebauthnCredential::findBy([MoWebauthnCredential::UID => $public_key_credential_user_entity->id]);
    foreach ($webauthn_credentials as $webauthn_credential) {
      $credential_sources[] = $this->generatePublicKeyCredentialSource($webauthn_credential);
    }

    return $credential_sources;
  }

  /**
   * {@inheritdoc}
   */
//  public function saveCredentialSource(PublicKeyCredentialSource $public_key_credential_source, $label = NULL): void {
//    $public_key_credential_id = base64_encode($public_key_credential_source->getPublicKeyCredentialId());
//    $webauthn_credential = MoWebauthnCredential::findOneBy([MoWebauthnCredential::CREDENTIAL_ID => $public_key_credential_id]);
//    if (!$webauthn_credential) {
//      $webauthn_credential = WebauthnCredential::create();
//    }
//    if (!empty($label)) {
//      $webauthn_credential->setLabel($label);
//    }
//    $webauthn_credential->setUid($public_key_credential_source->getUserHandle());
//    $webauthn_credential->setCredentialId($public_key_credential_id);
//    $webauthn_credential->setCredential(json_encode($public_key_credential_source));
//    $webauthn_credential->save();
//  }

}
