using Fido2NetLib;
using Fido2NetLib.Objects;
using System;
using System.Collections.Generic;
using System.Text.Json;

namespace Dacryptero.Session.Fido;

public static class Converter
{
    public static AuthenticatorAttestationRawResponse GetAuthenticatorAttestationRawResponse(JsonElement json)
    {
        return new AuthenticatorAttestationRawResponse
        {
            Id = json.GetProperty("id").GetBytesFromBase64(),
            RawId = json.GetProperty("rawId").GetBytesFromBase64(),
            Type = GetPublicKeyCredentialType(json.GetProperty("type")),
            Response = GetAttestationResponseData(json.GetProperty("response")),
        };
    }

    public static PublicKeyCredentialType GetPublicKeyCredentialType(JsonElement json)
    {
        return json.GetString() switch
        {
            "public-key" => PublicKeyCredentialType.PublicKey,
            _ => throw new KeyNotFoundException(),
        };
    }

    public static AuthenticatorAttestationRawResponse.ResponseData GetAttestationResponseData(JsonElement json)
    {
        return new AuthenticatorAttestationRawResponse.ResponseData
        {
            AttestationObject = json.GetProperty("attestationObject").GetBytesFromBase64(),
            ClientDataJson = json.GetProperty("clientDataJSON").GetBytesFromBase64(),
        };
    }

    public static AuthenticatorAssertionRawResponse GetAuthenticatorAssertionRawResponse(JsonElement json)
    {
        return new AuthenticatorAssertionRawResponse
        {
            Id = json.GetProperty("id").GetBytesFromBase64(),
            RawId = json.GetProperty("rawId").GetBytesFromBase64(),
            Type = GetPublicKeyCredentialType(json.GetProperty("type")),
            Response = GetAssertionResponseData(json.GetProperty("response"))
        };
    }

    public static AuthenticatorAssertionRawResponse.AssertionResponse GetAssertionResponseData(JsonElement json)
    {
        return new AuthenticatorAssertionRawResponse.AssertionResponse
        {
            AuthenticatorData = json.GetProperty("authenticatorData").GetBytesFromBase64(),
            ClientDataJson = json.GetProperty("clientDataJSON").GetBytesFromBase64(),
            Signature = json.GetProperty("signature").GetBytesFromBase64(),
            UserHandle = json.GetProperty("userHandle").GetBytesFromBase64(),
        };
    }
}