import { BaseResponse } from "../../../models/response/base.response";
import { Utils } from "../../../platform/misc/utils";

/**
 * WebAuthn credential-creation options minted by the server. Implements the
 * `PublicKeyCredentialCreationOptions` shape consumed by `navigator.credentials.create()`.
 *
 * Reused by both the 2FA settings flow (wrapped in `TwoFactorWebAuthnChallengeResponse`)
 * and the passkey-login flow (wrapped in `WebauthnLoginCredentialCreateOptionsResponse`).
 */
export class WebAuthnChallengeResponse
  extends BaseResponse
  implements PublicKeyCredentialCreationOptions
{
  attestation?: AttestationConveyancePreference;
  authenticatorSelection?: AuthenticatorSelectionCriteria;
  challenge: BufferSource;
  excludeCredentials?: PublicKeyCredentialDescriptor[];
  extensions?: AuthenticationExtensionsClientInputs;
  pubKeyCredParams: PublicKeyCredentialParameters[];
  rp: PublicKeyCredentialRpEntity;
  timeout?: number;
  user: PublicKeyCredentialUserEntity;

  constructor(response: any) {
    super(response);
    this.attestation = this.getResponseProperty("attestation");
    this.authenticatorSelection = this.getResponseProperty("authenticatorSelection");
    this.challenge = Utils.fromUrlB64ToArray(this.getResponseProperty("challenge")) as BufferSource;
    this.excludeCredentials = this.getResponseProperty("excludeCredentials").map((c: any) => {
      c.id = Utils.fromUrlB64ToArray(c.id).buffer;
      return c;
    });
    this.extensions = this.getResponseProperty("extensions");
    this.pubKeyCredParams = this.getResponseProperty("pubKeyCredParams");
    this.rp = this.getResponseProperty("rp");
    this.timeout = this.getResponseProperty("timeout");

    const user = this.getResponseProperty("user");
    user.id = Utils.fromUrlB64ToArray(user.id);

    this.user = user;
  }
}
