using System;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Dacryptero.Notifications;
using Dacryptero.DB.Creation;

namespace Dacryptero.Web.Events.Receive;

public class DatabaseAddRequest : ReceiveBase
{
    public string Database { get; private set; } = "";

    public string Schema { get; private set; } = "";

    private static Regex ValidDBName = new Regex(@"^[\w-]+$", RegexOptions.Compiled);

    public override async Task Execute(ExecuteArgs args)
    {
        // verify the database name
        if (args.Connection.DB.GetController(Database) is not null)
        {
            args.SendNotification(Notification.Error(
                "Cannot create DB",
                "DB name already in use"
            ));
            return;
        }
        if (!ValidDBName.IsMatch(Database))
        {
            args.SendNotification(Notification.Error(
                "Cannot create DB",
                "Invalid DB name"
            ));
            return;
        }

        // verify the schema
        if (!Data.Schema.SchemaCollection.Schemas.ContainsKey(Schema))
        {
            args.SendNotification(Notification.Error(
                "Cannot create DB",
                "Schema not found"
            ));
            return;
        }

        string key;
        NewDBInfo info;
        var rng = new Random();
        while (!args.Connection.NewDBInfo.TryAdd(
            key = NewDBInfo.GenerateKey(rng),
            info = new NewDBInfo(key, Database, Schema)
        ));

        await args.Connection.Send(new Send.DatabaseAddRequestInfo(info))
            .ConfigureAwait(false);
    }

    public override void ReadJsonContent(JsonElement json)
    {
        Database = json.GetProperty("database").GetString() ?? "";
        Schema = json.GetProperty("schema").GetString() ?? "";
    }
}