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

namespace Insight.Web.Pages.Management.HostGroups;

[Route(Navigation.Management.HostGroups.Details)]
public partial class Details
{
    [Parameter] public string? GroupId { get; set; }

    [Inject] private IMongoDatabase Database { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;
    [Inject] private NavigationManager NavigationManager { get; init; } = default!;

    private readonly List<BreadcrumbItem> _breadcrumbs = new();

    private string _title = Global.Name;
    private HostGroupEntity? _model;

    private async Task LoadDataAsync()
    {
        _model = null;

        _breadcrumbs.Clear();
        _breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        _breadcrumbs.Add(new BreadcrumbItem("Host Groups", href: Navigation.Management.HostGroups.Index));

        StateHasChanged();

        if (string.IsNullOrWhiteSpace(GroupId))
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.HostGroups.Index);
            return;
        }

        _model = await Database.HostGroup()
            .Aggregate()
            .Match(Builders<HostGroupEntity>.Filter.Eq(p => p.Id, GroupId))
            .FirstOrDefaultAsync(default);

        if (_model is null)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.HostGroups.Index);
            return;
        }

        _title = $"Host Groups » {_model.Name}｜Insight";
        _breadcrumbs.Add(new BreadcrumbItem(_model.Name, href: "#", true));

        await InvokeAsync(StateHasChanged);
    }
}