using Insight.Infrastructure.Entities;
using Insight.Web.Constants;
using Microsoft.AspNetCore.Components;
using MongoDB.Driver;
using MudBlazor;

namespace Insight.Web.Pages.Management.Agents;

public partial class AgentDeleteDialog
{
    [Parameter] public EventCallback OnChanges { get; set; }

    [Inject] private IMongoDatabase Database { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;
    [Inject] private ILogger<AgentDeleteDialog> Logger { get; init; } = default!;

    private AgentEntity? _model;

    public async void ToggleAsync(string? id)
    {
        if (id is null) return;

        try
        {
            _model = await Database.Agent().Find(p => p.Id == id).FirstAsync();
            _visible = !_visible;
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
        }

        await InvokeAsync(StateHasChanged);
    }

    private async Task SubmitAsync()
    {
        if (_model is null) return;

        try
        {
            await Database.Agent()
                .DeleteOneAsync(Builders<AgentEntity>
                .Filter.Eq(p => p.Id, _model.Id),
                cancellationToken: default).ConfigureAwait(false);

            await Database.Host()
                .UpdateOneAsync(Builders<HostEntity>
                .Filter
                .Eq(p => p.Agent, _model.Id), Builders<HostEntity>
                .Update
                .Set(p => p.Agent, null))
                .ConfigureAwait(false);

            Notification.Success(Snackbar);

            if (OnChanges.HasDelegate)
            {
                await InvokeAsync(async () =>
                {
                    await OnChanges.InvokeAsync(this);
                });
            }
        }
        catch (Exception ex)
        {
            Notification.Error(Snackbar);
            Logger.LogError(ex.ToString());
        }
        finally
        {
            _visible = false;
        }
    }
}