using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text.Json;

namespace Dacryptero.DB.Creation;

public class NewDBInfo
{
    public string Key { get; }

    public string Name { get; }

    public string Schema { get; }

    public ReadOnlyMemory<byte> MasterKey { get; }

    public List<DBAccess> Accesses { get; }
        = new List<DBAccess>();

    public NewDBInfo(string key, string name, string schema)
    {
        Key = key;
        Name = name;
        Schema = schema;
        MasterKey = GenerateMasterKey();
    }

    public static string GenerateKey(Random rng)
    {
        Span<byte> buffer = stackalloc byte[16];
        rng.NextBytes(buffer);
        return Convert.ToBase64String(buffer);
    }

    private static ReadOnlyMemory<byte> GenerateMasterKey()
    {
        return RandomNumberGenerator.GetBytes(80);
    }

    public void WriteTo(Utf8JsonWriter w)
    {
        w.WriteStartObject();
        w.WriteString("key", Key);
        w.WriteString("database", Name);
        w.WriteString("schema", Schema);
        w.WriteStartArray("access");
        foreach (var acess in Accesses)
            acess.WriteWebTo(w);
        w.WriteEndArray();
        w.WriteEndObject();
    }
}