using System;
using System.Text.Json;
using System.Threading.Tasks;
using Dacryptero.Notifications;

namespace Dacryptero.Web.Events.Receive;

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

    public Guid UserId { get; private set; }

    public override async Task Execute(ExecuteArgs args)
    {
        var controller = args.Connection.DB.GetController(Database);
        if (controller is null)
        {
            args.SendNotification(Notification.Error(
                "User deletion failed",
                "Database not found"
            ));
            return;
        }

        controller.Config.Access.RemoveAll(x => x.UserId == UserId);
        await controller.Config.SaveAsync()
            .ConfigureAwait(false);
        
        await args.Connection.Send(new Send.InfoSend(args.Connection))
            .ConfigureAwait(false);
    }

    public override void ReadJsonContent(JsonElement json)
    {
        Database = json.GetProperty("database").GetString() ?? "";
        UserId = json.GetProperty("user-id").GetGuid();
    }
}