using System;
using System.Security.Cryptography;
using System.Text.Json;
using System.Threading.Tasks;
using Fido2NetLib;

namespace Dacryptero.Session.Fido;

public abstract class UserBase
{
    public ReadOnlyMemory<byte> Challenge { get; }

    public Web.WebSocketConnection Connection { get; }

    public Fido2Configuration Configuration { get; }

    public UserBase(Web.WebSocketConnection connection, Fido2Configuration configuration)
    {
        Connection = connection;
        Configuration = configuration;

        Memory<byte> challenge = new byte[1024];
        RandomNumberGenerator.Fill(challenge.Span);
        Challenge = challenge;
    }

    public static Fido2Configuration GetConfiguration(string host)
    {
        var ind = host.LastIndexOf(':');
        var trimmedHost = ind >= 0 ? host.Remove(ind) : host;

        return new Fido2Configuration()
        {
            ServerDomain = trimmedHost,
            ServerName = trimmedHost,
            Origin = "http://" + host,
            Timeout = 60000,
        };
    }

    public abstract (string method, JsonElement data) GetMessage();

    public abstract Task<string?> ValidateResult(JsonElement data);
}